System.Data.IDataReader Interface
Overview
The System.Data.IDataReader
interface provides a way of reading a forward-only stream of data rows from a data source. It is implemented by data providers such as SqlDataReader
and OleDbDataReader
.
Syntax
public interface IDataReader : IDisposable, IDataRecord
{
// Properties
int Depth { get; }
bool IsClosed { get; }
int RecordsAffected { get; }
int FieldCount { get; }
// Methods
void Close();
DataTable GetSchemaTable();
bool NextResult();
bool Read();
// ... inherited members from IDataRecord
}
Properties
Property | Type | Description |
---|---|---|
Depth | int | Gets the depth of nesting for tables in the data source. |
FieldCount | int | Gets the number of columns in the current row. |
IsClosed | bool | Indicates whether the IDataReader is closed. |
RecordsAffected | int | Gets the number of rows changed, inserted, or deleted by execution of the SQL statement. |
Methods
Method | Signature | Description |
---|---|---|
Close | void Close() | Closes the IDataReader object. |
Read | bool Read() | Advances the reader to the next record. |
NextResult | bool NextResult() | Advances the reader to the next result set. |
GetSchemaTable | DataTable GetSchemaTable() | Retrieves schema information for the column metadata. |
Example
This example shows how to use SqlDataReader
, which implements IDataReader
, to read data from a SQL Server database.
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connString = "Data Source=.;Initial Catalog=Northwind;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT ProductID, ProductName FROM Products", conn))
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int id = reader.GetInt32(0);
string name = reader.GetString(1);
Console.WriteLine($"{id}: {name}");
}
}
}
}
}