22
COURSE NAME: Computer Programming II – C# with Database COURSE CODE: CPRG2301 TOPIC: Querying a Database in C# LECTURE 15 SQL (Structured Query Language) Statements CREATE TABLE The SQL syntax for CREATE TABLE is CREATE TABLE "table_name" ("column 1" "data_type_for_column_1", "column 2" "data_type_for_column_2", ... ) So, if we are to create the customer table specified as above, we would type in: CREATE TABLE customer (First_Name char(50), Last_Name char(50), Address char(50), City char(50), Country char(25), Birth_Date date) INSERT INTO STATEMENT The syntax for inserting data into a table one row at a time is as follows: INSERT INTO "table_name" ("column1", "column2", ...) VALUES ("value1", "value2", ...) Assuming that we have a table that has the following structure, 1

Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

  • Upload
    lammien

  • View
    234

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

COURSE NAME: Computer Programming II – C# with Database

COURSE CODE: CPRG2301

TOPIC: Querying a Database in C#

LECTURE 15

SQL (Structured Query Language) Statements

CREATE TABLE

The SQL syntax for CREATE TABLE is

CREATE TABLE "table_name"("column 1" "data_type_for_column_1","column 2" "data_type_for_column_2",... )

So, if we are to create the customer table specified as above, we would type in:

CREATE TABLE customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date date)

INSERT INTO STATEMENT

The syntax for inserting data into a table one row at a time is as follows:

INSERT INTO "table_name" ("column1", "column2", ...)VALUES ("value1", "value2", ...)

Assuming that we have a table that has the following structure,

Table Store_Information

Column Name Data Type

store_name char(50)

Sales float

1

Page 2: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

Date datetime

and now we wish to insert one additional row into the table representing the sales data for Los Angeles on January 10, 1999. On that day, this store had $900 in sales. We will hence use the following SQL script:

INSERT INTO Store_Information (store_name, Sales, Date)VALUES ('Los Angeles', 900, 'Jan-10-1999')

SELECT STATEMENT

SELECT "column_name" FROM "table_name"

To illustrate the above example,

Table Store_Information

store_name Sales Date

Los Angeles $1500 Jan-05-1999

San Diego $250 Jan-07-1999

Los Angeles $300 Jan-08-1999

Boston $700 Jan-08-1999

We shall use this table as an example. To select all the stores in this table, we key in,

SELECT store_name FROM Store_Information

Result:

store_nameLos AngelesSan DiegoLos AngelesBoston

Multiple column names can be selected, as well as multiple table names.

2

Page 3: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

Next, we might want to conditionally select the data from a table. For example, we may want to only retrieve stores with sales above $1,000. To do this, we use the WHERE keyword. The syntax is as follows:

SELECT "column_name"FROM "table_name"WHERE "condition"

For example, to select all stores with sales above $1,000 in Table Store_Information,

Table Store_Information

store_name Sales Date

Los Angeles $1500 Jan-05-1999

San Diego $250 Jan-07-1999

Los Angeles $300 Jan-08-1999

Boston $700 Jan-08-1999

we key in,

SELECT store_nameFROM Store_InformationWHERE Sales > 1000

Result:store_nameLos Angeles

SELECT * From Store_Information

The above statement will display all records (rows) and columns from the Store_Information table. The * is called a wildcard operator.

UPDATE STATEMENT

Once there's data in the table, we might find that there is a need to modify the data. To do so, we can use the UPDATE command. The syntax for this is

UPDATE "table_name"SET "column_1" = [new value]WHERE {condition}

3

Page 4: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

For example, say we currently have a table as below:

Table Store_Information

store_name Sales Date

Los Angeles $1500 Jan-05-1999

San Diego $250 Jan-07-1999

Los Angeles $300 Jan-08-1999

Boston $700 Jan-08-1999

We notice that the sales for Los Angeles on 01/08/1999 are actually $500 instead of $300, and that particular entry needs to be updated. To do so, we use the following SQL:

UPDATE Store_InformationSET Sales = 500WHERE store_name = "Los Angeles"AND Date = "Jan-08-1999"

It is also possible to UPDATE multiple columns at the same time. The syntax in this case would look like the following:

UPDATE "table_name"SET column_1 = [value1], column_2 = [value2]WHERE {condition}

DELETE FROM STATEMENT

Sometimes we may wish to get rid of records from a table. To do so, we can use the DELETE FROM command. The syntax for this is

DELETE FROM "table_name"WHERE {condition}

It is easiest to use an example. Say we currently have a table as below:

Table Store_Information

store_name Sales Date

Los Angeles $1500 Jan-05-1999

4

Page 5: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

San Diego $250 Jan-07-1999

Los Angeles $300 Jan-08-1999

Boston $700 Jan-08-1999

and we decide not to keep any information on Los Angeles in this table. To accomplish this, we type the following SQL:

DELETE FROM Store_InformationWHERE store_name = "Los Angeles"

Now the content of table would look like,

Table Store_Information

store_name Sales Date

San Diego $250 Jan-07-1999

Boston $700 Jan-08-1999

Introduction to LINQ Queries (C#)

LINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it does. The Language Integrated part means that LINQ is part of programming language syntax. In particular, both C# and VB are languages that ship with .NET and have LINQ capabilities. 

A query is an expression that retrieves data from a data source. Queries are usually expressed in a specialized query language. Different languages have been developed over time for the various types of data sources, for example SQL for relational databases and XQuery for XML.

Therefore, developers have had to learn a new query language for each type of data source or data format that they must support. LINQ simplifies this situation by offering a consistent model for working with data across various kinds of data sources and formats. In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, .NET collections, and any other format for which a LINQ provider is available.

5

Page 6: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

Advantages of LINQ Query is integrated into the language. Gone are the days of writing a SQL query into a

string and not detecting a syntax error until runtime, for example we forget the name of a field of the table (or reference) or it has been changed in DB.

In addition to query features, LINQ to XML provides a more powerful and easier-to-use interface for working with XML data, as though it were a database.

LINQ simplifies this situation by offering a consistent model for working with data across various kinds of data sources and formats.

Three Parts of a Query Operation

All LINQ query operations consist of three distinct actions:1. Obtain the data source.2. Create the query.3. Execute the query.

The following example shows how the three parts of a query operation are expressed in source code. The example uses an integer array as a data source for convenience; however, the same concepts apply to other data sources also. This example is referred to throughout the rest of this topic.

C# class IntroToLINQ{ static void Main() { // The Three Parts of a LINQ Query:  // 1. Data source.  int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

// 2. Query creation.  // numQuery is an IEnumerable<int>  var numQuery = from num in numbers where (num % 2) == 0 select num;

// 3. Query execution.  foreach (int num in numQuery) { Console.Write("{0} ", num); } }}

6

Page 7: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

The following illustration shows the complete query operation. In LINQ the execution of the query is distinct from the query itself; in other words you have not retrieved any data just by creating a query variable.

The Data SourceIn the previous example, because the data source is an array, it implicitly supports the generic IEnumerable<T> interface. This fact means it can be queried with LINQ. A query is executed in a foreach statement, and foreach requires IEnumerable or IEnumerable<T>. Types that support IEnumerable<T> or a derived interface such as the generic IQueryable<T> are called queryable types.

LINQ to SQL Statements

This section will discuss some of the common techniques used in LINQ to SQL statement construction. In a nutshell, LINQ to SQL provides the developer with the means to conduct queries against a relational database through a LINQ to SQL database model and related data context.

Data Context

The data context provides the mapping of all entities (essentially tables) to the database. It is through the data context that the application can query the database, and it is through the data context that changes to the database can be executed.

7

Page 8: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

Anatomy of LINQ to SQL Statements

Example 1 – A Simple Selectpublic void SimpleQuery(){ DataClasses1DataContext dc = new DataClasses1DataContext();

var q = from a in dc.GetTable<Order>() select a;

dataGridView1.DataSource = q;}

In the example, an instance of the data context is created, and then a query is formed to get all of the values in the table; once the query runs, the result is used as the data source of a DataGridView control, and the results are displayed in the grid:

var q = from a in dc.GetTable<Order>() select a;

Since the GetTable function in the data context returns the entire table, it is representative of a simple select query. You could accomplish the same task using this code:

public void SimpleQuery2(){ DataClasses1DataContext dc = new DataClasses1DataContext(); dataGridView1.DataSource = dc.GetTable<Order>();}

If you were to create a project, add either bit of code to a method and run it, the results would look like this:

Figure 2: Query Results

8

Page 9: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

Example 2 – Select with a Where Clause

The next example shows a LINQ to SQL query that incorporates a where clause. In this example, we get a data context to work with first, and then query the Orders table to find a customer with the customer ID starting with the letter “A”; the results are then bound to a DataGridView control.

public void SimpleQuery3(){ DataClasses1DataContext dc = new DataClasses1DataContext();

var q = from a in dc.GetTable<Order>() where a.CustomerID.StartsWith("A") select a;

dataGridView1.DataSource = q;}

If you were to run the query, the results would appear as follows:

Figure 3: Query Results

Example 3 – Select with a Where Clause

In a slight variation to the previous query, this example looks for an exact match in its where clause:

public void SimpleQuery3(){

9

Page 10: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

DataClasses1DataContext dc = new DataClasses1DataContext();

var q = from a in dc.GetTable<Order>() where a.CustomerID == "VINET" select a;

dataGridView1.DataSource = q;}

Running this code will display this result:

Figure 4: Query Results

Example 4 – Generating an Ordered ListIn this query, the list of orders is ordered (using “orderby a.OrderDate ascending”):public void SimpleQuery5(){ DataClasses1DataContext dc = new DataClasses1DataContext();

var q = from a in dc.GetTable<Order>() where a.CustomerID.StartsWith("A") orderby a.OrderDate ascending select a;

dataGridView1.DataSource = q;}

10

Page 11: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

Figure 5: Query Results

SELECT Statement in LINQ

Let's say I want to write a C# Expression and a C# statement where I have a table in SQL server named Products and I want to pull all rows where price is greater than 50. How would I write it?

from p in Productswhere p.Price > 50select p

Example using an Array as a Data Sourceclass LowNums{ static void Main() { // A simple data source.  int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

// Create the query.  // lowNums is an IEnumerable<int>  var lowNums = from num in numbers where num < 5 select num;

// Execute the query. 

11

Page 12: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

foreach (int i in lowNums) { Console.Write(i + " "); } } }// Output: 4 1 3 2 0

Example

The following query asks for a list of customers from London. In this example, Customers is a table in the Northwind sample database.

Northwnd db = new Northwnd(@"c:\northwnd.mdf");

// Query for customers in London.IQueryable<Customer> custQuery = from cust in db.Customers where cust.City == "London"  select cust;

12

Page 13: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

Let Clause

In a query expression, it is sometimes useful to store the result of a sub-expression in order to use it in subsequent clauses. You can do this with the let keyword, which creates a new range variable and initializes it with the result of the expression you supply. Once initialized with a value, the range variable cannot be used to store another value. However, if the range variable holds a queryable type, it can be queried.

Example

In the following example let is used in two ways:

1. To create an enumerable type that can itself be queried.2. To enable the query to call ToLower only one time on the range variable word. Without

using let, you would have to call ToLower in each predicate in thewhere clause.3. class LetSample14. {5. static void Main()6. {7. string[] strings = 8. {9. "A penny saved is a penny earned.",10. "The early bird catches the worm.",11. "The pen is mightier than the sword." 12. };13.14. // Split the sentence into an array of words 15. // and select those whose first letter is a vowel. 16. var earlyBirdQuery =17. from sentence in strings18. let words = sentence.Split(' ')19. from word in words20. let w = word.ToLower()21. where w[0] == 'a' || w[0] == 'e'22. || w[0] == 'i' || w[0] == 'o'23. || w[0] == 'u'24. select word;25.26. // Execute the query. 27. foreach (var v in earlyBirdQuery)28. {29. Console.WriteLine("\"{0}\" starts with a vowel", v);30. }31.32. // Keep the console window open in debug mode.33. Console.WriteLine("Press any key to exit.");

13

Page 14: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

34. Console.ReadKey();35. }36. }37. /* Output:38. "A" starts with a vowel39. "is" starts with a vowel40. "a" starts with a vowel41. "earned." starts with a vowel42. "early" starts with a vowel43. "is" starts with a vowel44. */

How to: Connect to a DatabaseThe DataContext is the main conduit by which you connect to a database, retrieve objects from it, and submit changes back to it. You use the DataContext just as you would use an ADO.NET SqlConnection. In fact, the DataContext is initialized with a connection or connection string that you supply.

The purpose of the DataContext is to translate your requests for objects into SQL queries to be made against the database, and then to assemble objects out of the results. The DataContext enables Language-Integrated Query (LINQ) by implementing the same operator pattern as the Standard Query Operators, such as Where and Select.

ExampleIn the following example, the DataContext is used to connect to the Northwind sample database and to retrieve rows of customers whose city is London.C#VB// DataContext takes a connection string. DataContext db = new DataContext(@"c:\Northwnd.mdf");

// Get a typed table to run queries.Table<Customer> Customers = db.GetTable<Customer>();

// Query for customers from London. var query = from cust in Customers where cust.City == "London"  select cust;

foreach (var cust in query) Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City);

Each database table is represented as a Table collection available by way of the GetTable method, by using the entity class to identify it.

14

Page 15: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

Best practice is to declare a strongly typed DataContext instead of relying on the basic DataContext class and the GetTable method. A strongly typed DataContext declares all Table collections as members of the context, as in the following example.

C#

public partial class Northwind : DataContext{ public Table<Customer> Customers; public Table<Order> Orders; public Northwind(string connection) : base(connection) { }}

You can then express the query for customers from London more simply as:

C#Northwnd db = new Northwnd(@"c:\Northwnd.mdf");var query = from cust in db.Customers where cust.City == "London"  select cust;foreach (var cust in query) Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City);

How to: Update Rows in the DatabaseYou can update rows in a database by modifying member values of the objects associated with the LINQ to SQL Table<TEntity> collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL UPDATE commands.

The following steps assume that a valid DataContext connects you to the Northwind database.

To update a row in the database1. Query the database for the row to be updated.2. Make desired changes to member values in the resulting LINQ to SQL object.3. Submit the changes to the database.

Example

15

Page 16: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

The following example queries the database for order #11000, and then changes the values of ShipName and ShipVia in the resulting Order object. Finally, the changes to these member values are submitted to the database as changes in the ShipName and ShipVia columns.C#

// Query the database for the row to be updated. var query = from ord in db.Orders where ord.OrderID == 11000 select ord;

// Execute the query, and change the column values // you want to change. foreach (Order ord in query){ ord.ShipName = "Mariner"; ord.ShipVia = 2; // Insert any additional changes to column values.}

// Submit the changes to the database. try{ db.SubmitChanges();}catch (Exception e){ Console.WriteLine(e); // Provide for exceptions.}

How to: Insert Rows into the DatabaseYou insert rows into a database by adding objects to the associated LINQ to SQL Table<TEntity> collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL INSERT commands.

To insert a row into the database1. Create a new object that includes the column data to be submitted.2. Add the new object to the LINQ to SQL Table collection associated with the target table

in the database.3. Submit the change to the database.

Example

16

Page 17: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

The following code example creates a new object of type Order and populates it with appropriate values. It then adds the new object to the Order collection. Finally, it submits the change to the database as a new row in the Orders table.C#

// Create a new Order object.Order ord = new Order{ OrderID = 12000, ShipCity = "Seattle", OrderDate = DateTime.Now // …};

// Add the new object to the Orders collection.db.Orders.InsertOnSubmit(ord);

// Submit the change to the database. try{ db.SubmitChanges();}catch (Exception e){ Console.WriteLine(e); // Make some adjustments.  // ...  // Try again. db.SubmitChanges();}

How to: Delete Rows from the DatabaseYou can delete rows in a database by removing the corresponding LINQ to SQL objects from their table-related collection. LINQ to SQL translates your changes to the appropriate SQL DELETE commands.

To delete a row in the database1. Query the database for the row to be deleted.2. Call the DeleteOnSubmit method.3. Submit the change to the database.

Example

17

Page 18: Introduction to LINQ Queries (C#) Prog II - C Sharp with DB...  · Web viewLINQ is an acronym for Language Integrated Query, which is descriptive for where it's used and what it

This first code example queries the database for order details that belong to Order #11000, marks these order details for deletion, and submits these changes to the database.C#

// Query the database for the rows to be deleted. var deleteOrderDetails = from details in db.OrderDetails where details.OrderID == 11000 select details;

foreach (var detail in deleteOrderDetails){ db.OrderDetails.DeleteOnSubmit(detail);}

try{ db.SubmitChanges();}catch (Exception e){ Console.WriteLine(e); // Provide for exceptions.}

References:

http://msdn.microsoft.com/en-us/library/bb386925(v=vs.110).aspx retrieved November 18, 2013

18