ADO.NET DataReader

The DataReader object provides a way to retrieve a forward-only, read-only stream of data from a data source. It is the most efficient way to retrieve data because it reads the data directly from the database without buffering it in memory. This makes it ideal for scenarios where you only need to process rows one at a time.

Understanding the DataReader

When you execute a query using a Command object and specify that you want to retrieve a result set, the data provider typically returns a DataReader. The DataReader cursor is positioned before the first row. You use the Read() method to advance to the next row. The Read() method returns true if there is another row to read, and false if there are no more rows.

Key Properties and Methods

Accessing Data

You can access the data within each column using various Get* methods. These methods allow you to retrieve data as specific .NET types. For example, GetString(int i), GetInt32(int i), GetDateTime(int i), etc.

Example Usage (C#)

using System;
using System.Data;
using System.Data.SqlClient; // Or your specific data provider

public class DataReaderExample
{
    public static void Main(string[] args)
    {
        string connectionString = "Your_Connection_String_Here";
        string query = "SELECT CustomerID, CompanyName FROM Customers";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand(query, connection))
            {
                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            int customerId = reader.GetInt32(0); // Get column by ordinal
                            string companyName = reader.GetString(reader.GetOrdinal("CompanyName")); // Get column by name

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

When to Use DataReader

Limitations

The DataReader is a forward-only stream. You cannot navigate backward to previous rows. If you need to go back and re-read data, you will need to re-execute the query or load the data into a DataSet.