An Easy Walk through the Data
As discussed earlier in this article, there are two ways to read and store data: one is DataSet and the other is DataReader. A data reader provides an easy way for the programmer to read data from a database as if it were coming from a stream. The DataReader is the solution for forward streaming data through ADO.NET. The data reader is also called a firehose cursor or forward read-only cursor because it moves forward through the data. The data reader not only allows you to move forward through each record of database, but it also enables you to parse the data from each column. The DataReader class represents a data reader in ADO.NET.
Similar to other ADO.NET objects, each data provider has a data reader class for example; OleDbDataReader is the data reader class for OleDb data providers. Similarly, SqlDataReader and ODBC DataReader are data reader classes for Sql and ODBC data providers, respectively.
The IDataReader interface defines the functionally of a data reader and works as the base class for all data provider-specific data reader classes such as OleDataReader. SqlDataReader, and OdbcDataReader. Figure 5-36 shows some of the classes that implement IDbDataReader.
Figure 5-36. Data Provider-specific classes implementing IdbDataReader
Initializing DataReader
As you've seen in the previous examples, you call the ExecuteReader method of the Command object, which returns an instance of the DataReader. For example, use the following line of code:
Dim cmd As New SqlCommand(Sql, conn)
' Call ExecuteReader to return a DataReader
Dim reader As SqlDataReader = cmd.ExecuteReader()
Once you're done with the data reader, call the Close method to close a data reader:
reader.Close()
DataReader Properties and Methods
Table 5-26 describes DataReader properties, and Table 5-27 describes DataReader methods.
Table 5-26. The DataReader properties
PROPERTY
|
DESCRIPTION
|
Depth
|
Indicates the depth of nesting for row
|
FieldCount
|
Returns number of columns in a row
|
IsClosed
|
Indicates whether a data reader is closed
|
Item
|
Gets the value of a column in native format
|
RecordsAffected
|
Number of row affected after a transaction
|
Table 5-27. The DataReader methods
METHOD
|
DESCRIPTION
|
Close
|
Closes a DataRaeder object.
|
Read
|
Reads next record in the data reader.
|
NextResult
|
Advances the data reader to the next result during batch transactions.
|
Getxxx
|
There are dozens of Getxxx methods. These methods read a specific data type value from a column. For example. GetChar will return a column value as a character and GetString as a string.
|
Reading with the DataReader
Once the OleDbDataReader is initialize, you can utilize its various methods to read your data records. Foremost, you can use the Read method, which, when called repeatedly, continues to read each row of data into the DataRader object. The DataReader also provides a simple indexer that enables you to pull each column of data from the row. Below is an example of using the DataReader in the Northwind database for the Customers table and displaying data on the console.
As you can see from listing 5-39, I've used similar steps as I've been using in previous examples. I created a connection object, created a command object, called the ExecuteReader method, called the DataReader's Read method until the end of the data, and then displayed the data. At the end, I released the data reader and connection objects.
Listing 5-39. DataReader reads data from a SQL server database
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Data.SqlClient
Namespace CommandTypeEnumeration
Class Program
Private Shared Sub Main(ByVal args As String())
' Create a connection string
Dim ConnectionString As String = "Integrated Security = SSPI; " & "Initial Catalog= Northwind; " & " Data source = localhost; "
Dim SQL As String = "SELECT * FROM Customers"
' create a connection object
Dim conn As New SqlConnection(ConnectionString)
' Create a command object
Dim cmd As New SqlCommand(SQL, conn)
conn.Open()
' Call ExecuteReader to return a DataReader
Dim reader As SqlDataReader = cmd.ExecuteReader()
Console.WriteLine("customer ID, Contact Name, " & "Contact Title, Address ")
Console.WriteLine("=============================")
While reader.Read()
Console.Write(reader("CustomerID").ToString() & ", ")
Console.Write(reader("ContactName").ToString() & ", ")
Console.Write(reader("ContactTitle").ToString() & ", ")
Console.WriteLine(reader("Address").ToString() & ", ")
End While
'Release resources
reader.Close()
conn.Close()
End Sub
End Class
End Namespace
Figure 5-37 shows the output of Listing 5-39.
Figure 5-37. Output of the Customers table from the DataReader
Other methods in the Reader allow you to get the value of a column as a specific type. For instance, this line from the previous example:
Dim str As String = reader("CustomerID").ToString()
Could be rewritten as this:
Dim str As String = reader.GetString(0)
With the GetString method of the CustomerID, you don't need to do any conversion, but you do have known the zero-based column number of the CustomerID (Which, in this case, is zero).
Interpreting Batched of Queries
DataReader also has methods that enable you read data from a batch of SQL queries. Below is an example of a batch transaction on the Customers and Orders table. The NextResult method allows you to obtain each query result from the batch of queries performed on both table. In this example, after creating a connection object, you set up your Command object to do a batch query on the Customers and the Orders tables:
Dim cmd As New SqlCommand("SELECT * FROM Customers; SELECT * FROM Orders", conn)
Now you can create the Reader through the Command object. You'll then use a result flag as an indicator to check if you've gone through all the results. Then you'll loop through each stream of results and read the data into a string until it reads 10 records. After that, you show results in a message box (see listing 5-40).
After that you call the NextResult method, which gets the next query result in the batch. The result is processed again in the Read method loop.
Listing 5-40. Executing batches using DataReader
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Data.SqlClient
Namespace CommandTypeEnumeration
Class Program
Private Shared Sub Main(ByVal args As String())
' Create a connection string
Dim ConnectionString As String = "Integrated Security = SSPI; " & "Initial Catalog= Northwind; " & "Data Source = localhost; "
Dim SQL As String = " SELECT * FROM Customers; SELECT * FROM Orders"
' Create a Conenction object
Dim conn As New SqlConnection(ConnectionString)
' Create a command object
Dim cmd As New SqlCommand(SQL, conn)
conn.Open()
' Call ExecuteReader to return a DataReader
Dim reader As SqlDataReader = cmd.ExecuteReader()
Dim counter As Integer = 0
Dim str As String = " "
Dim bNextResult As Boolean = True
While bNextResult = True
While reader.Read()
str += reader.GetValue(0).ToString() & vbLf
counter += 1
If counter = 10 Then
Exit While
End If
End While
MessageBox.Show(str)
bNextResult = reader.NextResult()
End While
' Release resources
reader.Close()
conn.Close()
End Sub
End Class
End Namespace
Figure 5-38 shows the two Message Boxes produced from this routine.
Figure 5-38. Output for the batch read of the Customers and Orders table
Conclusion
Hope this article would have helped you in understanding DataReader in ADO.NET. See my other articles on the website on ADO.NET.