MSDN Documentation

Windows Programming / Data Access

DataReader Object

The DataReader object provides a way to retrieve a forward-only, read-only stream of data from a data source. It's a performant mechanism for consuming data when you don't need the full functionality of a dataset, such as client-side manipulation or navigation.

Purpose and Benefits

Key Methods and Properties

Commonly used members of the DataReader object include:

Example Usage (C# with ADO.NET)

Here's a basic example demonstrating how to use DataReader to fetch data from a SQL Server database:


using System;
using System.Data;
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 query = "SELECT CustomerID, CompanyName, ContactName FROM Customers";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand(query, connection))
            {
                try
                {
                    connection.Open();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                Console.WriteLine($"ID: {reader.GetInt32(0)}, Company: {reader.GetString(1)}, Contact: {reader.GetString(2)}");
                            }
                        }
                        else
                        {
                            Console.WriteLine("No rows found.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("An error occurred: " + ex.Message);
                }
            }
        }
    }
}
            

Important Considerations

Always wrap your DataReader and connection objects in using statements to ensure proper disposal of resources, even if errors occur.

Comparison with DataSet

While DataSet is suitable for disconnected scenarios, caching data, and complex data manipulation, DataReader excels when you need to iterate through results quickly and efficiently without the overhead of a full dataset. Choose the tool that best fits your specific data access needs.

Related Topics