Databases Reference
In-Depth Information
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.
n Tip One point that we'll discuss further in the next chapter is choosing a data reader vs. a dataset. 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.
Let's say you've successfully established a connection with the database, a query has
been executed, and everything seems to be going fine—what now? The next sensible
thing to do would be to retrieve the rows and process them.
Try It Out: Looping Through a Result Set
The following console application shows how to use a SqlDataReader to loop through
a result set and retrieve rows.
1. Create a new Console Application project named Chapter12. When Solution
Explorer opens, save the solution.
2. Rename the Chapter12 project to DataLooper. Rename the Program.cs file to
DataLooper.cs , and replace the generated code with the code in Listing 12-1.
Listing 12-1. DataLooper.cs
using System;
using System.Data;
using System.Data.SqlClient;
Search WWH ::




Custom Search