ADO.NET DataReaders

This document provides an in-depth overview of ADO.NET DataReaders, a crucial component for efficient data retrieval from databases in .NET applications.

What is a DataReader?

A DataReader object provides a way to retrieve a forward-only, read-only stream of data from a data source. It's designed for performance, offering a lightweight and fast way to access query results. Unlike DataSet objects, DataReaders do not load the entire result set into memory at once. Instead, they read rows one by one as you iterate through them.

Key Features and Benefits

Using DataReaders

The most common DataReader implementations are SqlDataReader (for SQL Server) and OdbcDataReader (for ODBC data sources).

Example: Retrieving Data with SqlDataReader

Here's a C# example demonstrating how to use a SqlDataReader to fetch data:

using System;
using System.Data.SqlClient;

public class DataReaderExample
{
    public static void ReadData(string connectionString)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            string query = "SELECT CustomerID, CompanyName FROM Customers";

            using (SqlCommand command = new SqlCommand(query, connection))
            {
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            // Access data by column name or ordinal index
                            string customerId = reader.GetString(0); // Index 0 for CustomerID
                            string companyName = reader.GetString(1); // Index 1 for CompanyName

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

    public static void Main(string[] args)
    {
        // Replace with your actual connection string
        string connStr = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
        ReadData(connStr);
    }
}

Key Methods and Properties

When to Use DataReaders

DataReaders are an excellent choice when:

Comparison with DataSet

While DataSet objects are useful for holding multiple tables, caching data, and allowing modifications, DataReader objects are optimized for streaming data. If you only need to iterate through results once, a DataReader is generally preferred.

Further Reading