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 (503.88 KB, 69 trang )
Data Binding
45
Dim strSQL As String = "SELECT * FROM Products"
Then, we open a new SQLConnection using the connection string.
Dim sqlConn As New SqlClient.SqlConnection(strConnection)
sqlConn.Open()
The myCommand data command is created by passing it the statement and connection strings. We can
then use myCommand to cause the DataReader to execute the SQL statement that we want – in this
case, to select all records from the Products table.
Dim myCommand As New SqlClient.SqlCommand(strSQL, sqlConn)
myCommand.CommandType = CommandType.Text
Dim myReader As SqlClient.SqlDataReader = myCommand.ExecuteReader()
However, as we learned previously, the DataReader retrieves the records one at a time in a forward-
only and read-only format.
The last part of code retrieves each record in the DataReader one at a time and writes the Product Id
and Product Name to the Output window using the Console.WriteLine method:
Do While myReader.Read
Console.WriteLine("Product Id: " & myReader.GetInt32(0) & _
vbTab & "Product Name: " & myReader.GetString(1))
Loop
Notice the use of the GetInt32 and GetString methods of the DataReader object. These methods
can be used because we know the data types of the underlying data fields. By explicitly using the typed
accessor methods in this way, we reduce the amount of type conversion that is required when retrieving
the data.
Last of all, we have the line that closes the DataReader.
myReader.Close()
It is very important to note that a DataReader is open until you close the connection with such a line
of code (or the object gets destroyed and thus the connection is closed at some point during garbage
collection).
You can modify this simple example for your own purposes, but this should give you an idea of how to
a DataReader can be used to rapidly retrieve forward-only, read-only data. The most important idea