Database Reference
In-Depth Information
Figure 14-2.
Looping through a result set using
DataReader
How It Works
SqlDataReader
is an abstract class and can't be instantiated explicitly. For this reason, you obtain an
instance of a
SqlDataReader
by executing the
ExecuteReader
method of
SqlCommand
.
// Create data reader
SqlDataReader rdr = cmd.ExecuteReader();
ExecuteReader()
doesn't just create a data reader; it sends the SQL to the connection for execution,
so when it returns, you can loop through each row of the result set and retrieve values column by
column. To do this, you call the
Read
method of
SqlDataReader
, which returns
true
if a row is available
and advances the
cursor
(the internal pointer to the next row in the result set) or returns
false
if another
row isn't available. Since
Read()
advances the cursor to the next available row, you have to call it for all
the rows in the result set, so you call it as the condition in a
while
loop.