Đang chuẩn bị liên kết để tải về tài liệu:
Executing SELECT Statements and TableDirect Commands phần 1
Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Executing SELECT Statements and TableDirect Commands A TableDirect command is actually a SELECT statement that returns all the rows and columns for a specified table. | Executing SELECT Statements and TableDirect Commands A TableDirect command is actually a SELECT statement that returns all the rows and columns for a specified table. A Command object has three methods you can use to execute a SELECT statement or TableDirect command. Table 8.4 shows these methods which you ll learn how to use in the following sections. Table 8.4 METHODS THAT RETRIEVE INFORMATION FROM THE DATABASE METHOD RETURN TYPE DESCRIPTION ExecuteReader SqlDataReader Used to execute SQL SELECT statements TableDirect commands or stored procedure calls that return a result set. Returns the result set in a DataReader object. ExecuteScalar object Used to execute SQL SELECT statements that return a single value any other values are ignored . Returns the single value as an object. ExecuteXmlReader XmlReader Used to execute SQL SELECT statements that return XML data. Returns the result set in an XmlReader object. Applies only to the SqlCommand class. Executing a SELECT Statement Using the ExecuteReader Method Let s take a look at an example that executes a SELECT statement using the ExecuteReader method. This method returns the result set in a DataReader object which you can then use to read the rows returned by the database. For example the following code creates the required objects and executes a SELECT statement that retrieves the top five rows from the Customers table SqlConnection mySqlConnection new SqlConnection server localhost database Northwind uid sa pwd sa SqlCommand mySqlCommand mySqlConnection.CreateCommand mySqlCommand.CommandText SELECT TOP 5 CustomerlD CompanyName ContactName Address FROM Customers ORDER BY CustomerlD mySqlConnection.Open SqlDataReader mySqlDataReader mySqlCommand.ExecuteReader Tip You ll notice that I didn t call the Open method of the SqlConnection object until just before calling the ExecuteReader method of the SqlCommand object. This is intentional. By opening the connection at the very last moment you minimize time spent .