System.Data.IDataReader Interface

Contents

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

PropertyTypeDescription
DepthintGets the depth of nesting for tables in the data source.
FieldCountintGets the number of columns in the current row.
IsClosedboolIndicates whether the IDataReader is closed.
RecordsAffectedintGets the number of rows changed, inserted, or deleted by execution of the SQL statement.

Methods

MethodSignatureDescription
Closevoid Close()Closes the IDataReader object.
Readbool Read()Advances the reader to the next record.
NextResultbool NextResult()Advances the reader to the next result set.
GetSchemaTableDataTable 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}");
                }
            }
        }
    }
}

See Also