1. Trang chủ
  2. » Công Nghệ Thông Tin

Executing Multiple SQL Statements

7 273 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Executing Multiple SQL Statements
Định dạng
Số trang 7
Dung lượng 30,86 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

In this section, you'll see how to execute multiple SELECT statements and retrieve results, and you'll see how to execute multiple SELECT, INSERT, UPDATE, and DELETE statements that are

Trang 1

Executing Multiple SQL Statements

Typically, your C# program and the database will run on different computers and

communicate over a network Each time you execute a command in your program, it has

to travel over the network to the database and be executed by the database, and any

results must be sent back across the network to your program That's a lot of network traffic! One way to potentially reduce network traffic is to execute multiple SQL

statements at a time

In this section, you'll see how to execute multiple SELECT statements and retrieve

results, and you'll see how to execute multiple SELECT, INSERT, UPDATE, and

DELETE statements that are interleaved

Executing Multiple SELECT Statements

Let's take a look at how you execute multiple SELECT statements and retrieve the

results The following code first creates a SqlCommand object named mySqlCommand and sets its CommandText property to three different SELECT statements:

SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

mySqlCommand.CommandText =

"SELECT TOP 5 ProductID, ProductName " +

"FROM Products " +

"ORDER BY ProductID;" +

"SELECT TOP 3 CustomerID, CompanyName " +

"FROM Customers " +

"ORDER BY CustomerID;" +

"SELECT TOP 6 OrderID, CustomerID " +

"FROM Orders " +

"ORDER BY OrderID;";

Notice that all of the SELECT statements are separated by semi-colons

Using Table Joins

Be careful to retrieve only the rows and columns you actually need Also, make sure you use SELECT statements that retrieve rows from multiple tables For example, if you want

to see all the orders placed by the customer with the CustomerID of ALFKI, don't

perform two separate SELECT statements against the Customers and Orders tables Instead, use a table join, as shown in the following SELECT statement:

Trang 2

SELECT Customers.CustomerID, CompanyName, OrderID

FROM Customers, Orders

WHERE Customers.CustomerID = Orders.CustomerID

AND Customers.CustomerID = 'ALFKI';

To run earlier SQL statements, you call the ExecuteReader() method, which returns a SqlDataReader object:

SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();

The command will return three result sets, one for each SELECT statement To read the first result set, you call the Read() method of mySqlDataReader The Read() method returns false when there are no more rows to read Once you're at the end of a result set, you call the NextResult() method of mySqlDataReader before reading the next result set The NextResult() method advances mySqlDataReader onto the next result set and returns false when there are no more result sets

The following code illustrates the use of the Read() and NextResult() methods to read the three result sets from the SELECT statements:

do

{

while (mySqlDataReader.Read())

{

Console.WriteLine("mySqlDataReader[0] = " +

mySqlDataReader[0]);

Console.WriteLine("mySqlDataReader[1] = " +

mySqlDataReader[1]);

}

} while (mySqlDataReader.NextResult());

Notice the use of the outer do…while loop, which tests the return value from

mySqlDataReader.NextResult() at the end Because a do…while loop checks the

condition at the end of the loop, this means that the statements in the do…while loop

execute at least once You want to put the call to NextResult() at the end because it first

attempts to advance mySqlDataReader to the next result set and then returns the Boolean result that indicates whether there is another result set to move to If you put the call to NextResult() in a regular while loop, then mySqlDataReader would skip over the first result set, and you don't want to do that!

Listing 9.4 illustrates how to execute multiple SELECT statements and read the results

Trang 3

Listing 9.4: EXECUTEMULTIPLESELECTS.CS

/*

ExecuteMultipleSelects.cs illustrates how to execute

multiple SELECT statements using a SqlCommand object

and read the results using a SqlDataReader object

*/

using System;

using System.Data;

using System.Data.SqlClient;

class ExecuteSelect

{

public static void Main()

{

SqlConnection mySqlConnection =

new SqlConnection(

"server=localhost;database=Northwind;uid=sa;pwd=sa"

);

SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

// set the CommandText property of the SqlCommand object to

// the mutliple SELECT statements

mySqlCommand.CommandText =

"SELECT TOP 5 ProductID, ProductName " +

"FROM Products " +

"ORDER BY ProductID;" +

"SELECT TOP 3 CustomerID, CompanyName " +

"FROM Customers " +

"ORDER BY CustomerID;" +

"SELECT TOP 6 OrderID, CustomerID " +

"FROM Orders " +

"ORDER BY OrderID;";

mySqlConnection.Open();

SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();

// read the result sets from the SqlDataReader object using

// the Read() and NextResult() methods

do

{

Trang 4

while (mySqlDataReader.Read())

{

Console.WriteLine("mySqlDataReader[0] = " +

mySqlDataReader[0]);

Console.WriteLine("mySqlDataReader[1] = " +

mySqlDataReader[1]);

}

Console.WriteLine(""); // visually split the results

} while (mySqlDataReader.NextResult());

mySqlDataReader.Close();

mySqlConnection.Close();

}

}

The output from this program is as follows:

mySqlDataReader[0] = 1

mySqlDataReader[1] = Chai

mySqlDataReader[0] = 2

mySqlDataReader[1] = Chang

mySqlDataReader[0] = 3

mySqlDataReader[1] = Aniseed Syrup

mySqlDataReader[0] = 4

mySqlDataReader[1] = Chef Anton's Cajun Seasoning

mySqlDataReader[0] = 5

mySqlDataReader[1] = Chef Anton's Gumbo Mix

mySqlDataReader[0] = ALFKI

mySqlDataReader[1] = Alfreds Futterkiste

mySqlDataReader[0] = ANATR

mySqlDataReader[1] = Ana Trujillo3 Emparedados y helados mySqlDataReader[0] = ANTON

mySqlDataReader[1] = Antonio Moreno Taquería

mySqlDataReader[0] = 10248

mySqlDataReader[1] = VINET

mySqlDataReader[0] = 10249

mySqlDataReader[1] = TOMSP

mySqlDataReader[0] = 10250

mySqlDataReader[1] = HANAR

mySqlDataReader[0] = 10251

Trang 5

mySqlDataReader[1] = VICTE

mySqlDataReader[0] = 10252

mySqlDataReader[1] = SUPRD

mySqlDataReader[0] = 10253

mySqlDataReader[1] = HANAR

Executing Multiple SELECT, INSERT, UPDATE, and DELETE Statements

You can interleave multiple SELECT, INSERT, UPDATE, and DELETE statements This can save network traffic because you're sending multiple SQL statements to the database in one go The following code first creates a SqlCommand object named

mySqlCommand and sets its CommandText property to multiple interleaved SQL

statements:

mySqlCommand.CommandText =

"INSERT INTO Customers (CustomerID, CompanyName) "+

"VALUES ('J5COM', 'Jason 5 Company');" +

"SELECT CustomerID, CompanyName " +

"FROM Customers " +

"WHERE CustomerID = 'J5COM';" +

"UPDATE Customers " +

"SET CompanyName = 'Another Jason Company' " +

"WHERE CustomerID = 'J5COM';" +

"SELECT CustomerID, CompanyName " +

"FROM Customers " +

"WHERE CustomerID = 'J5COM';" +

"DELETE FROM Customers " +

"WHERE CustomerID = 'J5COM';";

The SQL statements are as follows:

• The INSERT statement adds a new row to the Customers table

• The first SELECT statement retrieves the new row

• The UPDATE statement modifies the CompanyName column of the row

• The second SELECT statement retrieves the row again

• The DELETE statement removes the row

You can use the same do…while loop as shown in the previous section to retrieve the two result sets returned by the SELECT statements The same loop works even though the example executes inter-leaved non-SELECT statements It works because only the

SELECT statements return result sets and the NextResult() method returns true only for the SELECT statements; it returns false for the other SQL statements Therefore,

Trang 6

NextResult() returns false for the INSERT statement and advances to result set for the first SELECT statement, and so on

Listing 9.5 illustrates how to execute multiple SQL statements

Listing 9.5: EXECUTEMULTIPLESQL.CS

/*

ExecuteMultipleSQL.cs illustrates how to execute

multiple SQL statements using a SqlCommand object

*/

using System;

using System.Data;

using System.Data.SqlClient;

class ExecuteMultipleSQL

{

public static void Main()

{

SqlConnection mySqlConnection =

new SqlConnection(

"server=localhost;database=Northwind;uid=sa;pwd=sa"

);

SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

// set the CommandText property of the SqlCommand object to

// the INSERT, UPDATE, and DELETE statements

mySqlCommand.CommandText =

"INSERT INTO Customers (CustomerID, CompanyName) " +

"VALUES ('J5COM', 'Jason 5 Company');" +

"SELECT CustomerID, CompanyName " +

"FROM Customers " +

"WHERE CustomerID = 'J5COM';" +

"UPDATE Customers " +

"SET CompanyName = 'Another Jason Company' " +

"WHERE CustomerID = 'J5COM';" +

"SELECT CustomerID, CompanyName " +

"FROM Customers " +

"WHERE CustomerID = 'J5COM';" +

"DELETE FROM Customers " +

"WHERE CustomerID = 'J5COM';";

mySqlConnection.Open();

Trang 7

SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();

// read the result sets from the SqlDataReader object using

// the Read() and NextResult() methods

do

{

while (mySqlDataReader.Read())

{

Console.WriteLine("mySqlDataReader[0] = " +

mySqlDataReader[0]);

Console.WriteLine("mySqlDataReader[1] = " +

mySqlDataReader[1]);

}

Console.WriteLine(""); // visually split the results

} while (mySqlDataReader.NextResult());

mySqlDataReader.Close();

mySqlConnection.Close();

}

}

The output from this program is as follows:

mySqlDataReader[0] = J5COM

mySqlDataReader[1] = Jason 5 Company

mySqlDataReader[0] = J5COM

mySqlDataReader[1] = Another Jason Company

Ngày đăng: 28/10/2013, 15:15

TỪ KHÓA LIÊN QUAN