MSDN Documentation

Using DataReader in ADO.NET

The DataReader object in ADO.NET provides a way to retrieve a forward-only, read-only stream of data from a data source. It's highly efficient for scenarios where you need to read data row by row without loading the entire dataset into memory.

What is DataReader?

DataReader is an interface that represents a data reader. The specific implementation depends on the data provider you are using (e.g., SqlDataReader for SQL Server, OdbcDataReader for ODBC). It allows you to iterate through the results of a query one record at a time.

Key Features:

How to Use DataReader:

The basic workflow involves executing a command that returns data, obtaining a DataReader object, reading the data row by row, and then closing the reader.

Example: Reading Data with SqlDataReader


using System;
using System.Data.SqlClient;

public class DataReaderExample
{
    public static void Main(string[] args)
    {
        string connectionString = "Server=myServerAddress;Database=myDatabase;User Id=myUsername;Password=myPassword;";
        string queryString = "SELECT ProductID, ProductName, UnitPrice FROM Production.Product;";

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

            try
            {
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        // Access data by column name or ordinal index
                        Console.WriteLine($"ID: {reader["ProductID"]}, Name: {reader["ProductName"]}, Price: {reader["UnitPrice"]}");
                        // Or by index: Console.WriteLine($"ID: {reader[0]}, Name: {reader[1]}, Price: {reader[2]}");
                    }
                }
                else
                {
                    Console.WriteLine("No rows found.");
                }
                reader.Close(); // Always close the reader
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
}
                

Key Methods and Properties:

Best Practice:

Always wrap your DataReader operations within a using statement for the connection and ensure you call reader.Close() (or let the using statement handle it if you use it for the reader as well) to release the database connection and resources promptly.

When to Use DataReader:

Alternatives:

For scenarios where you need to work with the data offline, bind data to UI controls, or perform complex data manipulation, consider using DataAdapter and DataTable or DataSet objects.