MSDN Documentation

Microsoft Developer Network

DataReaders in ADO.NET

ADO.NET DataReaders provide a forward-only, read-only stream of data from a data source. They are highly efficient for scenarios where you need to retrieve data quickly and process it row by row without needing to load the entire dataset into memory. This makes them ideal for tasks like populating grids, performing iterative calculations, or generating reports.

What is a DataReader?

A DataReader is an object that implements the IDataReader interface. The most common implementations you'll encounter are:

The core functionality is consistent across these implementations, allowing for a largely database-agnostic approach when working with them.

Key Features and Benefits

Using a DataReader

The typical workflow for using a DataReader involves the following steps:

  1. Establish a connection to the data source.
  2. Create a command object.
  3. Execute the command using ExecuteReader(), which returns a DataReader object.
  4. Iterate through the rows using a while (reader.Read()) loop.
  5. Access column values within the loop using appropriate methods (e.g., reader["ColumnName"], reader.GetString(index), reader.GetInt32(index)).
  6. Close the DataReader and the connection when finished.

Example: Retrieving Product Names from a Database


using System;
using System.Data;
using System.Data.SqlClient; // For SQL Server

public class ProductReader
{
    public void GetProductNames(string connectionString)
    {
        string query = "SELECT ProductName, UnitPrice FROM Products";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand(query, connection))
            {
                try
                {
                    connection.Open();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                string productName = reader.GetString(reader.GetOrdinal("ProductName"));
                                decimal unitPrice = reader.GetDecimal(reader.GetOrdinal("UnitPrice"));

                                Console.WriteLine($"Product: {productName}, Price: {unitPrice:C}");
                            }
                        }
                        else
                        {
                            Console.WriteLine("No products found.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
    }
}
            

Common DataReader Methods