Wednesday, June 15, 2005
For data retrieval with low overhead, give the DataReader a try
The DataSet is probably the most common tool for handling datain .NET. However, if you only need to retrieve small amounts ofdata for the purpose of displaying it, all the overhead of theDataSet to support two-way communication between the database andyour .NET program is unnecessary. With the .NET DataReader, youcan retrieve a read-only, forward-only stream of data and dump itout one row at a time.
The first few steps for creating a DataReader should soundfamiliar. You start with a Connection, pass it aConnectionString, create a Command object, and open theConnection. From this point, to retrieve the data, you just needto call the ExecuteReader command. The following lines of codeillustrates the process if you were working with a SQL database:
Dim cn As SqlConnection =New SqlConnection("server=svr1;" _
"uid=uid1;pwd=pw1;database=yoursqldb")
Dim myCMD As SqlCommand = _
New SqlCommand("SELECT * FROM SomeTable", cn)
myCMD.CommandType = CommandType.Text
cn.Open
Dim myReader As SqlDataReader = _
myCMD.ExecuteReader(CommandBehavior.CloseConnection)
Once you create the SQLDataReader, you'll treat it just like youwould a Recordset in classic ADO. You repeatedly call the Read()method until the DataReader retrieves all the rows. A While loop,similar to the one in the next set of code, works wonderfully:
Do While myReader.Read()
'get data
Loop
The first few steps for creating a DataReader should soundfamiliar. You start with a Connection, pass it aConnectionString, create a Command object, and open theConnection. From this point, to retrieve the data, you just needto call the ExecuteReader command. The following lines of codeillustrates the process if you were working with a SQL database:
Dim cn As SqlConnection =New SqlConnection("server=svr1;" _
"uid=uid1;pwd=pw1;database=yoursqldb")
Dim myCMD As SqlCommand = _
New SqlCommand("SELECT * FROM SomeTable", cn)
myCMD.CommandType = CommandType.Text
cn.Open
Dim myReader As SqlDataReader = _
myCMD.ExecuteReader(CommandBehavior.CloseConnection)
Once you create the SQLDataReader, you'll treat it just like youwould a Recordset in classic ADO. You repeatedly call the Read()method until the DataReader retrieves all the rows. A While loop,similar to the one in the next set of code, works wonderfully:
Do While myReader.Read()
'get data
Loop