Sunday, September 23, 2007

The DataReader Class

A DataReader allows you to read the data returned by a SELECT command one record at a time, in a forward-only, read-only stream. This is sometimes called a firehose cursor. Using a DataReader is the simplest way to get to your data, but it lacks the sorting and relational abilities of the disconnected DataSet described in Chapter 8. However, the DataReader provides the quickest possible no-nonsense access to data.

Read() Advances the row cursor to the next row in the stream. This method must also be called before reading the first row of data. (When the DataReader is first created, the row cursor is positioned just before
the first row.) The Read() method returns true if there’s another row
to be read, or false if it’s on the last row.
GetValue() Returns the value stored in the field with the specified column name or index, within the currently selected row. The type of the returned value is the closest .NET match to the native value stored in the data source. If you access the field by index and inadvertently पास an invalid index that refers to a nonexistent field, you will get an
IndexOutOfRangeException exception. You can also access the same
value by name, which is slightly less efficient because the DataReader
must perform a lookup to find the column with the specified name.
GetValues() Saves the values of the current row into an array. The number of fields that are saved depends on the size of the array you pass to this method. You can use the DataReader.FieldCount property to
determine the number of fields in a row, and you can use that
information to create an array of the right size if you want to save
all the fields.

No comments: