Database Reference
In-Depth Information
C H A P T E R 14
Using Data Readers
In Chapter 13, you used data readers to retrieve data from a multirow result set. In this chapter, we'll
look at data readers in more detail. You'll see how they're used and their importance in ADO.NET
programming.
In this chapter, we'll cover the following:
•
Understanding data readers in general
•
Getting data about data
•
Getting data about tables
•
Using multiple result sets with a data reader
Understanding Data Readers in General
The third component of a data provider, after connections and commands, is the
data reader.
Once
you've connected to a database and queried it, you need some way to access the result set. This is where
the data reader comes in.
Data readers are objects that implement the
System.Data.IDataReader
interface. A data reader is a
fast, unbuffered, forward-only, read-only
connected
stream that retrieves data on a per-row basis. It
reads one row at a time as it loops through a result set.
You can't directly instantiate a data reader; instead, you create one with the
ExecuteReader
method
of a command. For example, assuming
cmd
is a
SqlClient
command object for a query, here's how to
create a
SqlClient
data reader:
SqlDataReader rdr = cmd.ExecuteReader();
You can now use this data reader to access the query's result set.
Tip
One point that we'll discuss further in the next chapter is choosing a data reader vs. a data set. The general
rule is to always use a data reader for simply retrieving data. If all you need to do is display data, all you need to
use in most cases is a data reader.
We'll demonstrate basic data reader usage with a few examples. The first example is the most basic;
it simply uses a data reader to loop through a result set.