MSDN Documentation

Data Access with ADO.NET

ADO.NET Data Readers

ADO.NET Data Readers provide a way to retrieve a forward-only, read-only stream of data from a data source. They are highly efficient for scenarios where you need to iterate through a result set without loading the entire dataset into memory. This makes them ideal for tasks like displaying lists of items, performing aggregations, or processing large volumes of data.

Key Features of Data Readers

Common Data Reader Classes

The specific Data Reader class you use depends on the data provider you are working with:

How to Use a Data Reader

The general pattern for using a Data Reader involves the following steps:

  1. Establish a connection to the data source.
  2. Create a command object with your SQL query.
  3. Associate the command with the connection.
  4. Execute the command using ExecuteReader(), which returns a Data Reader object.
  5. Iterate through the result set using a while loop and the Read() method.
  6. Access column values using their ordinal index or column name.
  7. Close the Data Reader and the connection when finished.

Example: Using SqlDataReader

Here's a C# example demonstrating the use of SqlDataReader:


using System;
using System.Data.SqlClient;

public class DataReaderExample
{
    public static void Main(string[] args)
    {
        string connectionString = "Your_Connection_String_Here";
        string queryString = "SELECT ProductID, ProductName, UnitPrice FROM Production.Products WHERE UnitPrice > $50.00;";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(queryString, connection);

            try
            {
                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            // Access data by ordinal index
                            int productId = reader.GetInt32(0);
                            string productName = reader.GetString(1);
                            decimal unitPrice = reader.GetDecimal(2);

                            Console.WriteLine($"ID: {productId}, Name: {productName}, Price: {unitPrice:C}");

                            // Alternatively, access data by column name
                            // int productId = reader.GetInt32(reader.GetOrdinal("ProductID"));
                            // string productName = reader.GetString(reader.GetOrdinal("ProductName"));
                            // decimal unitPrice = reader.GetDecimal(reader.GetOrdinal("UnitPrice"));
                        }
                    }
                    else
                    {
                        Console.WriteLine("No rows found.");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
            // The 'using' statement ensures the connection is closed even if an exception occurs.
        }
    }
}
            

Important Considerations

Performance Benefits

The primary advantage of Data Readers lies in their performance. By avoiding the overhead of creating and populating DataSet and DataTable objects, Data Readers can significantly speed up data retrieval operations, especially for large datasets or when only a subset of data is needed for immediate processing.