DataReader Object

The DataReader object in ADO.NET provides a way to read a forward-only stream of data rows from a data source. It's highly efficient for retrieving data when you only need to iterate through the results once, without the overhead of loading the entire dataset into memory.

Key Characteristics and Usage

The DataReader object offers several advantages:

Creating and Using a DataReader

You typically obtain a DataReader by executing a command against a database using a Connection object.

Example: Retrieving Data with SqlDataReader

The following C# code snippet demonstrates how to use the SqlDataReader (a specific implementation for SQL Server):


using System;
using System.Data.SqlClient;

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

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string sqlQuery = "SELECT CustomerID, CompanyName FROM Customers";

            using (SqlCommand command = new SqlCommand(sqlQuery, connection))
            {
                try
                {
                    connection.Open();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                // Access data by column name or ordinal position
                                Console.WriteLine($"CustomerID: {reader["CustomerID"]}, CompanyName: {reader["CompanyName"]}");
                                // Or by ordinal position (0-based index)
                                // Console.WriteLine($"CustomerID: {reader.GetInt32(0)}, CompanyName: {reader.GetString(1)}");
                            }
                        }
                        else
                        {
                            Console.WriteLine("No rows found.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
    }
}
            

Common Methods and Properties

Here are some of the most frequently used members of the DataReader object:

Important: Always ensure that you close your DataReader (or wrap it in a using statement) to release the database connection and resources promptly.

When to Use DataReader

The DataReader is the optimal choice when:

For scenarios where you need to bind data to UI controls, perform complex data manipulation, or work with disconnected data, DataSet or DataTable might be more suitable.