Using a DataReader Object to Retrieve Data

Using a DataReader Object to Retrieve Data

The DataReader object is used to retrieve data in a forward-only, read-only stream. With it, you can get quick and efficient access to your data. To create a DataReader object, call the ExecuteReader method of the Command object instead of using a constructor. You can read each row of data in the current dataset using the Read method of the DataReader class. This method will return true as long as data is available to be read; it will return false if no more data is available.

The data from each column of the returned row can be read using the various Get methods. Each method returns a particular column as a particular data type. For example, the GetSqlString method of the SqlDataReader class returns a column as a SqlString, which represents a variable-length string. Similarly, the GetSqlInt32 method returns the column value as a SqlInt32, which represents a 32-bit integer. Each of these methods takes the zero-based column ordinal as its parameter. For example, calling GetSqlInt32(0) will return the value of the first column in the current row as a 32-bit integer. The following code illustrates how to read data from SQL Server using the DataReader object:

SqlCommand cmd = new SqlCommand("SELECT * FROM authors");


SqlDataReader rdr = cmd.ExecuteReader();

    string firstCol = rdr.GetSqlString(0);
    int secondCol = rdr.GetSqlInt32(1);
    //Get other columns using the Get methods
    //and take action.


If the DataReader object holds multiple result sets, you can move to the next set of data by calling the NextResult method.

Part III: Programming Windows Forms