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
FieldCount
: Returns the number of columns in the result set.GetOrdinal(string fieldName)
: Returns the zero-based column ordinal of the specified column name.IsDBNull(int i)
: Checks if the specified column contains a null value.Read()
: Advances the DataReader to the next record.Close()
: Closes the DataReader object.
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
- When you need to read a large result set efficiently, and you don't need to manipulate the data in memory.
- When you need to perform actions row by row without the overhead of creating
DataRow
objects or filling aDataSet
. - For scenarios like reporting, data export, or simple data display where a live connection and immediate data access are paramount.
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
.