MSDN Documentation

Working with DataReaders

DataReaders provide a lightweight, forward-only, read-only stream of data from a data source. They are an efficient way to retrieve data when you only need to read through a result set once, without the overhead of creating a DataSet. This section explores the concepts and usage of DataReader objects in ADO.NET.

What is a DataReader?

A DataReader object (such as SqlDataReader for SQL Server or OleDbDataReader for OLE DB providers) is instantiated by executing a command that returns a result set. It allows you to iterate through the rows of the result set one by one, accessing column values for each row. Key characteristics include:

When to Use a DataReader

DataReader is ideal for scenarios where:

Creating a DataReader

To create a DataReader, you typically follow these steps:

  1. Establish a connection to the data source.
  2. Create a Command object with your SQL query.
  3. Associate the Command object with the connection.
  4. Execute the command using the ExecuteReader() method of the Command object.

Example: Retrieving Data with SqlDataReader


using System;
using System.Data;
using System.Data.SqlClient;

public class DataReaderExample
{
    public static void Main(string[] args)
    {
        string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            string sql = "SELECT CustomerID, CompanyName, ContactName FROM Customers;";
            using (SqlCommand command = new SqlCommand(sql, connection))
            {
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            // Access data by column name or ordinal index
                            int customerId = reader.GetInt32(reader.GetOrdinal("CustomerID"));
                            string companyName = reader.GetString(reader.GetOrdinal("CompanyName"));
                            string contactName = reader.GetString(reader.GetOrdinal("ContactName"));

                            Console.WriteLine($"ID: {customerId}, Company: {companyName}, Contact: {contactName}");
                        }
                    }
                    else
                    {
                        Console.WriteLine("No rows found.");
                    }
                }
            }
        }
    }
}
                

Note: The using statements ensure that resources like connections and readers are properly disposed of, even if errors occur.

Reading Data with DataReader

The primary methods for reading data are:

Important Note on Closing

A DataReader must be explicitly closed to release the database connection. The using statement is the recommended way to ensure this happens automatically.

Advanced DataReader Techniques

Tip: Using GetOrdinal

It's a good practice to use reader.GetOrdinal("ColumnName") to get the zero-based ordinal index of a column. This makes your code more resilient to changes in the order of columns in your SQL query compared to hardcoding ordinal indices.

Conclusion

DataReader objects are a fundamental part of ADO.NET for efficient, forward-only data retrieval. By understanding their behavior and using them correctly, you can build high-performance data-driven applications.

Next: Data Access with DataSets