ADO.NET. Industrial Programming. Structure of database access. ADO.NET Example. Lecture 7: Database access in C# using LINQ



Similar documents
Web Development using PHP (WD_PHP) Duration 1.5 months

Seminar Datenbanksysteme

A table is a collection of related data entries and it consists of columns and rows.

A Brief Introduction to MySQL

: provid.ir

ASP.NET Programming with C# and SQL Server

Application note: Connecting the to a Database

Concepts Design Basics Command-line MySQL Security Loophole

Beginning C# 5.0. Databases. Vidya Vrat Agarwal. Second Edition

SQL Injection. SQL Injection. CSCI 4971 Secure Software Principles. Rensselaer Polytechnic Institute. Spring

Visual C# 2012 Programming

Facebook Twitter YouTube Google Plus Website

Connecting to a Database Using PHP. Prof. Jim Whitehead CMPS 183, Spring 2006 May 15, 2006

MYSQL DATABASE ACCESS WITH PHP

Utilizing SFTP within SSIS

SQL. Short introduction

Database: SQL, MySQL

7 Web Databases. Access to Web Databases: Servlets, Applets. Java Server Pages PHP, PEAR. Languages: Java, PHP, Python,...

David M. Kroenke and David J. Auer Database Processing 11 th Edition Fundamentals, Design, and Implementation. Chapter Objectives

Server side scripting and databases

Mul$media im Netz (Online Mul$media) Wintersemester 2014/15. Übung 03 (Nebenfach)

HIGH PERFORMANCE PROGRAMMING FOR SHAREPOINT DEVELOPERS. DEV213 Eric Shupps, Microsoft MVP [SharePoint]

LSINF1124 Projet de programmation

DIPLOMA IN WEBDEVELOPMENT

PHP Language Binding Guide For The Connection Cloud Web Services

Each Ad Hoc query is created by making requests of the data set, or View, using the following format.

A Tutorial on SQL Server CMPT 354 Fall 2007

Skills for Employment Investment Project (SEIP)

Web Application diploma using.net Technology

Chapter 22 Database: SQL, MySQL,

Secure Authentication and Session. State Management for Web Services

Unified access to all your data points. with Apache MetaModel

LINQ: Language Integrated Query. ST Colloquium, Tom Lokhorst

Equipment Room Database and Web-Based Inventory Management

Databases and SQL. Homework. Matthias Danner. June 11, Matthias Danner Databases and SQL June 11, / 16

Liberty Alliance. CSRF Review. .NET Passport Review. Kerberos Review. CPSC 328 Spring 2009

Application Development

Other Language Types CMSC 330: Organization of Programming Languages

Getting Started with MongoDB

Paging, sorting, and searching using EF Code first and MVC 3. Introduction. Installing AdventureWorksLT database. Creating the MVC 3 web application

Zend Framework Database Access

Serious Threat. Targets for Attack. Characterization of Attack. SQL Injection 4/9/2010 COMP On August 17, 2009, the United States Justice

Using Microsoft SQL Server A Brief Help Sheet for CMPT 354

SQL Injection. The ability to inject SQL commands into the database engine through an existing application

David M. Kroenke and David J. Auer Database Processing 12 th Edition

CSCI110 Exercise 4: Database - MySQL

relational database tables row column SQL

SQL 2: GETTING INFORMATION INTO A DATABASE. MIS2502 Data Analytics

Advanced Object Oriented Database access using PDO. Marcus Börger

Using Database Metadata and its Semantics to Generate Automatic and Dynamic Web Entry Forms

Oracle Database 10g Express

INSTALLING, CONFIGURING, AND DEVELOPING WITH XAMPP

SQL: Programming. Introduction to Databases CompSci 316 Fall 2014

A basic create statement for a simple student table would look like the following.

Linas Virbalas Continuent, Inc.


Deleting A Record Updating the Database Binding Data Tables to Controls Binding the Data Table to the Data Grid View...

Database Master User Manual

The Whole OS X Web Development System

7- PHP and MySQL queries

Database Management System Choices. Introduction To Database Systems CSE 373 Spring 2013

Relational Database Basics Review

Writing Scripts with PHP s PEAR DB Module

How To Create A Table In Sql (Ahem)

Apache Tuscany RDB DAS

CSCI110: Examination information.

SQL and programming languages

Creating the Product Catalog Part I (continued)

Integrating Big Data into the Computing Curricula

How To Design Your Code In Php (Php)

Web Application Development

ASP.NET Using C# (VS2012)

Advanced SQL. Jim Mason. Web solutions for iseries engineer, build, deploy, support, train

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

Token Payment Web Services

Intro to Embedded SQL Programming for ILE RPG Developers

II. PREVIOUS RELATED WORK

COSC 6397 Big Data Analytics. 2 nd homework assignment Pig and Hive. Edgar Gabriel Spring 2015

WEB DEVELOPMENT COURSE (PHP/ MYSQL)

Intro to Databases. ACM Webmonkeys 2011

1 Introduction. 3 Open Mobile IS components 3.1 Embedded Database 3.2 Web server and Servlet API 3.3 Service API and template engine

Beginning MYSQL 5.0. With. Visual Studio.NET 2005

Visual Basic. murach's TRAINING & REFERENCE

MS 20487A Developing Windows Azure and Web Services

Java EE Web Development Course Program

Outline. SAS-seminar Proc SQL, the pass-through facility. What is SQL? What is a database? What is Proc SQL? What is SQL and what is a database

Qualtrics Single Sign-On Specification

SQL. by Steven Holzner, Ph.D. ALPHA. A member of Penguin Group (USA) Inc.

The JAVA Way: JDBC and SQLJ

VB.NET - DATABASE ACCESS

MySQL for Beginners Ed 3

Transcription:

ADO.NET Industrial Programming Lecture 7: Database access in C# using LINQ Industrial Programming 1 ADO.NET provides a direct interface to a database. The interface is database-specific. ADO.NET uses a conventional, shallow embedding of SQL commands into C# as host language, i.e. SQL commands are composed as strings A more advanced, deep embedding of SQL commands is provided by LINQ, i.e. SQL commands a language constructs Industrial Programming 2 Structure of database access To access a database with ADO.NET the following steps are necessary: Connect to a database Compose an SQL query Issue the query Retrieve and process the results Disconnect from the database. ADO.NET To connect to a database, a connection string has to specify location, account, password etc. (fill in user id and pwd) using MySql.Data.MySqlClient; string cstr = "Server=anubis;Database=test;User ID=;Password="; MySqlConnection dbcon; try { dbcon = new MySqlConnection(cstr); dbcon.open(); catch (MySql.Data.MySqlClient.MySqlException ex) { Industrial Programming 3 Industrial Programming 4

ADO.NET (cont'd) Next, compose an SQL query as a string This can be any SQL operation Depending on the underlying database, SQL extensions might be available. MySqlCommand dbcmd = dbcon.createcommand(); string sql = "SELECT A_ID, A_FNAME, A_LNAME " + "FROM authors"; dbcmd.commandtext = sql; ADO.NET (cont'd) Next, issue the query, and process the result, typically in a while loop. MySqlDataReader reader = dbcmd.executereader(); while(reader.read()) { string FirstName = (string) reader["a_fname"]; string LastName = (string) reader["a_lname"]; Console.WriteLine("Name: " + FirstName + " " + LastName); Industrial Programming 5 Industrial Programming 6 ADO.NET (cont'd) Finally, clean-up and disconnect. reader.close(); reader = null; dbcmd.dispose(); dbcmd = null; dbcon.close(); dbcon = null; Industrial Programming 7 LINQ Language Integrated Query (LINQ) is a more advanced way to interact with databases. It's a new feature with C# 3.0 onwards. It provides SQL-like commands as language extensions, rather than composing SQL queries as strings (deep embedding) It can also be used to access other forms of data, such as XML data or compound C# Industrial Programming 8

LINQ The same example as before, written in LINQ is much simpler. First, classes, representing the tables of the database are defined. [Table(Name = "authors")] public class Authors { public int A_ID { get ; set ; public string A_FNAME { get ; set ; public string A_LNAME { get ; set ; Industrial Programming 9 LINQ (cont'd) Next, a connection is established, using a connection string similar to ADO.NET. DataContext db = new DataContext("Data Source =.\\MySql;" + "Initial Catalog=test;Integrated Security=True"); DataContext db = new DataContext(connStr); Industrial Programming 10 LINQ (cont'd) The main advantage of LINQ is the simplified way of performing queries. Note, that SQL-like commands such as select, from etc are directly available Table<Authors> AuthorTable = db.gettable<authors>(); List<Authors> dbquery = from author in Authors select author ; foreach (var author in dbquery) { Console.WriteLine("Author: "+author.a_fname+" + author.a_lname); Industrial Programming 11 Querying in-memory Data LINQ can also be used to query in-memory data, such as XML data or compound C# This results in more uniform and succinct code. Using LINQ in this way requires several advanced language features. It is an alternative to using standard mechanisms of traversing data structures such as iterators. Industrial Programming 12

Assume we have a list of books: List<Book> booklist = new List<Book> { new Book { Title = "Learning C#", Author = "Jesse Liberty", Year = 2008, new Book { Title = "Programming C#", Author = "Jesse Liberty", Year = 2008, new Book { Title = "Programming PHP", Author = "Rasmus Lerdorf, Kevin Tatroe", Year = 2006, The conventional way to iterate over the list looks like this: foreach (Book b in booklist) { if (b.author == "Jesse Liberty") { Console.WriteLine(b.Title + " by " + b.author); ; Industrial Programming 13 Industrial Programming 14 In contrast, the LINQ-style iteration looks like an SQL query and is shorter: IEnumerable<Book> resultsauthor = where b.author == "Jesse Liberty" select b; Console.WriteLine("LINQ query: find by author..."); foreach (Book r in resultsauthor) { To avoid returning entire book results from the query we can use anonymous types and just return title and author: var resultsauthor1 =// NB: this needs to infer the type (anonymous!) where b.author == "Jesse Liberty" select new { b.title, b.author ; // NB: anonymous type here! foreach (var r in resultsauthor1) { Industrial Programming 15 Industrial Programming 16

Lambda expressions can be used to shorten the query even further: var resultsauthor2 = // NB: lambda expression here booklist.where(bookeval => bookeval.author == "Jesse Liberty"); foreach (var r in resultsauthor2) { We can sort the result by author: var resultsauthor3 = orderby b.author select new { b.title, b.author ; // NB: anonymous type here! Console.WriteLine("LINQ query: ordered by author..."); foreach (var r in resultsauthor3) { Industrial Programming 17 Industrial Programming 18 We can join tables like this: var resultlist4 = join p in purchaselist on b.title equals p.title where p.quantity >=2 select new { b.title, b.author, p.quantity ; Console.WriteLine("LINQ query: ordered by author..."); foreach (var r in resultlist4) { Console.WriteLine(r.Quantity + " items of " + r.title + " by " + r.author); Summary C# supports two ways of querying databases: ADO.NET with SQL queries as strings LINQ with SQL commands embedded into the language ADO.NET is older and more robust LINQ is newer and easier to use LINQ can also be used to traverse in-memory Industrial Programming 19 Industrial Programming 20