CHAPTER 21 ADO.NET PART I: THE CONNECTED LAYER
provider in the background. With this first example behind you, you can now dive into the details of
working with the connected layer of ADO.NET.
Note Now that you understand the role of ADO.NET data provider factories, the remaining examples in this
book will focus on the task at hand by explicitly using the types within the System.Data.SqlClient namespace. If
you use a different database management system (such as Oracle), you need to update your code base
accordingly.
Source Code You can find the DataProviderFactory project under the Chapter 21 subdirectory.
Understanding the Connected Layer of ADO.NET
Recall that the connected layer of ADO.NET allows you to interact with a database using the connection,
command, and data reader objects of your data provider. You have already used these objects in the
previous DataProviderFactory application, and now you’ll walk through the process again, this time
using an expanded example. You need to perform the following steps when you want to connect to a
database and read the records using a data reader object:
•
Allocate, configure, and open your connection object.
•
Allocate and configure a command object, specifying the connection object as
a constructor argument or with the Connection property.
•
Call ExecuteReader() on the configured command class.
•
Process each record using the Read() method of the data reader.
To get the ball rolling, create a new Console Application named AutoLotDataReader and import the
System.Data and System.Data.SqlClient namespaces. Here is the complete code within Main() (analysis
will follow):
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Data Readers *****\n");
// Create and open a connection.
using(SqlConnection cn = new SqlConnection())
{
cn.ConnectionString =
@"Data Source=(local)\SQLEXPRESS;Integrated Security=SSPI;" +
"Initial Catalog=AutoLot";
cn.Open();
830