Tải bản đầy đủ (.pdf) (10 trang)

Executing SELECT Statements and TableDirect Commands phần 1

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (39.33 KB, 10 trang )

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 CustomerID, CompanyName, ContactName, Address " +
"FROM Customers " +
"ORDER BY CustomerID";
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 connected to the database and therefore conserve database resources.
The result set returned by mySqlCommand is stored in mySqlDataReader. You then read
the rows from mySqlDataReader using the Read() method. This method returns the
Boolean true value when there is another row to read, otherwise it returns false. You can
read an individual column value in a row from mySqlDataReader by passing the name of
the column in square brackets. For example, to read the CustomerID column, you use
mySqlDataReader["CustomerID"].

Note You can also specify the column you want to get by passing a numeric value in
brackets. For example, my SqlDataReader[0] also returns the CustomerID column
value. 0 corresponds to the first column in the table, which in this example is the
CustomerID column.
You can use the Read() method in a while loop to read each row in turn, as shown in the
following example:
while (mySqlDataReader.Read())
{
Console.WriteLine("mySqlDataReader[\" CustomerID\"] = " +
mySqlDataReader["CustomerID"]);
Console.WriteLine("mySqlDataReader[\" CompanyName\"] = " +

mySqlDataReader["CompanyName"]);
Console.WriteLine("mySqlDataReader[\" ContactName\"] = " +
mySqlDataReader["ContactName"]);
Console.WriteLine("mySqlDataReader[\" Address\"] = " +
mySqlDataReader["Address"]);
}

Listing 8.1
illustrates a complete program that uses the code examples shown in this
section.
Listing 8.1: EXECUTESELECT.CS

/*
ExecuteSelect.cs illustrates how to execute a SELECT
statement using a SqlCommand object
*/

using System;
using System.Data;
using System.Data.SqlClient;

class ExecuteSelect
{
public static void Main()
{
// create a SqlConnection object to connect to the database
SqlConnection mySqlConnection =
new SqlConnection(
"server=localhost;database=Northwind;uid=sa;pwd=sa"
);


// create a SqlCommand object
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

// set the CommandText property of the SqlCommand object to
// the SELECT statement
mySqlCommand.CommandText =
"SELECT TOP 5 CustomerID, CompanyName, ContactName, Address " +
"FROM Customers " +
"ORDER BY CustomerID";

// open the database connection using the
// Open() method of the SqlConnection object
mySqlConnection.Open();

// create a SqlDataReader object and call the ExecuteReader()
// method of the SqlCommand object to run the SQL SELECT statement
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();

// read the rows from the SqlDataReader object using
// the Read() method
while (mySqlDataReader.Read())
{
Console.WriteLine("mySqlDataReader[\" CustomerID\"] = " +
mySqlDataReader["CustomerID"]);
Console.WriteLine("mySqlDataReader[\" CompanyName\"] = " +
mySqlDataReader["CompanyName"]);
Console.WriteLine("mySqlDataReader[\" ContactName\"] = " +
mySqlDataReader["ContactName"]);
Console.WriteLine("mySqlDataReader[\" Address\"] = " +

mySqlDataReader["Address"]);
}

// close the SqlDataReader object using the Close() method
mySqlDataReader.Close();

// close the SqlConnection object using the Close() method
mySqlConnection.Close();
}
}

The output from this program is as follows:
mySqlDataReader["CustomerID"] = ALFKI
mySqlDataReader["CompanyName"] = Alfreds Futterkiste
mySqlDataReader["ContactName"] = Maria Anders
mySqlDataReader["Address"] = Obere Str. 57
mySqlDataReader["CustomerID"] = ANATR
mySqlDataReader["CompanyName"] = Ana Trujillo3 Emparedados y helados
mySqlDataReader["ContactName"] = Ana Trujillo
mySqlDataReader["Address"] = Avda. de la Constitución 2222
mySqlDataReader["CustomerID"] = ANTON
mySqlDataReader["CompanyName"] = Antonio Moreno Taquería
mySqlDataReader["ContactName"] = Antonio Moreno
mySqlDataReader["Address"] = Mataderos 2312
mySqlDataReader["CustomerID"] = AROUT
mySqlDataReader["CompanyName"] = Around the Horn
mySqlDataReader["ContactName"] = Thomas Hardy
mySqlDataReader["Address"] = 120 Hanover Sq.
mySqlDataReader["CustomerID"] = BERGS
mySqlDataReader["CompanyName"] = Berglunds snabbköp

mySqlDataReader["ContactName"] = Christina Berglund
mySqlDataReader["Address"] = Berguvsvägen 8
Controlling the Command Behavior Using the ExecuteReader() Method
The ExecuteReader() method accepts an optional parameter that controls the command
behavior. The values for this parameter come from the System.Data.CommandBehavior
enumeration, for which values are shown in Table 8.5
.
Table 8.5: CommandBehavior ENUMERATION VALUES
VALUE DESCRIPTION
Table 8.5: CommandBehavior ENUMERATION VALUES
VALUE DESCRIPTION
CloseConnection Specifies that when the associated DataReader object is closed, the
Connection object is also closed.
Default Indicates the Command object may return multiple result sets.
KeyInfo Specifies the Command object returns information about the primary
key columns in the result set.
SchemaOnly Indicates the Command object returns information only about the
columns.
SequentialAccess Enables a DataReader object to read rows that have columns
containing large binary values. SequentialAccess causes the
DataReader to read the data as a stream. You then use the GetBytes()
or GetChars() methods of the DataReader to read the stream. Note:
you'll learn the details of DataReader objects in the next chapter
.
SingleResult Specifies the Command object returns a single result set.
SingleRow Indicates the Command object returns a single row.
You'll see how to use the SingleRow and SchemaOnly command behaviors next.
Using the SingleRow Command Behavior
You use the SingleRow command behavior to indicate that your Command object returns
a single row. For example, let's say you have a Command object named mySqlCommand

with the CommandText property set as follows:
mySqlCommand.CommandText =
"SELECT ProductID, ProductName, QuantityPerUnit, UnitPrice " +
"FROM Products";
Next, the following example passes the CommandBehavior.SingleRow value to the
ExecuteReader() method, indicating that the Command object retrieves only the first row:
SqlDataReader mySqlDataReader =
mySqlCommand.ExecuteReader(CommandBehavior.SingleRow);
Even though the earlier SELECT statement indicates that all the rows are to be retrieved
from the Products table, the mySqlDataReader object will be able to read only the first
row.
Listing 8.2
illustrates the effect of using CommandBehavior.SingleRow.

×