SqlDataReader SqlDataReader SqlDataReader SqlDataReader Class

Definition

Provides a way of reading a forward-only stream of rows from a SQL Server database. This class cannot be inherited.

public ref class SqlDataReader : System::Data::Common::DbDataReader, IDisposable
public class SqlDataReader : System.Data.Common.DbDataReader, IDisposable
type SqlDataReader = class
    inherit DbDataReader
    interface IDataReader
    interface IDisposable
    interface IDataRecord
Public Class SqlDataReader
Inherits DbDataReader
Implements IDisposable
Inheritance
Implements

Examples

The following example creates a SqlConnection, a SqlCommand, and a SqlDataReader. The example reads through the data, writing it out to the console window. The code then closes the SqlDataReader. The SqlConnection is closed automatically at the end of the using code block.

using System;
using System.Data;
using System.Data.SqlClient;


class Program
{
    static void Main()
    {
        string str = "Data Source=(local);Initial Catalog=Northwind;"
            + "Integrated Security=SSPI";
        ReadOrderData(str);
    }

    private static void ReadOrderData(string connectionString)
    {
        string queryString =
            "SELECT OrderID, CustomerID FROM dbo.Orders;";

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

            SqlDataReader reader = command.ExecuteReader();

            // Call Read before accessing data.
            while (reader.Read())
            {
                ReadSingleRow((IDataRecord)reader);
            }

            // Call Close when done reading.
            reader.Close();
        }
    }

    private static void ReadSingleRow(IDataRecord record)
    {
        Console.WriteLine(String.Format("{0}, {1}", record[0], record[1]));
    }

}
Option Explicit On
Option Strict On

Imports System.Data
Imports System.Data.SqlClient

Module Module1

    Sub Main()
        Dim str As String = "Data Source=(local);Initial Catalog=Northwind;" _
       & "Integrated Security=SSPI;"
        ReadOrderData(str)
    End Sub

    Private Sub ReadOrderData(ByVal connectionString As String)
        Dim queryString As String = _
            "SELECT OrderID, CustomerID FROM dbo.Orders;"

        Using connection As New SqlConnection(connectionString)
            Dim command As New SqlCommand(queryString, connection)
            connection.Open()

            Dim reader As SqlDataReader = command.ExecuteReader()

            ' Call Read before accessing data.
            While reader.Read()
                ReadSingleRow(CType(reader, IDataRecord))
            End While

            ' Call Close when done reading.
            reader.Close()
        End Using
    End Sub

    Private Sub ReadSingleRow(ByVal record As IDataRecord)
       Console.WriteLine(String.Format("{0}, {1}", record(0), record(1)))

    End Sub

End Module

Remarks

To create a SqlDataReader, you must call the ExecuteReader method of the SqlCommand object, instead of directly using a constructor.

While the SqlDataReader is being used, the associated SqlConnection is busy serving the SqlDataReader, and no other operations can be performed on the SqlConnection other than closing it. This is the case until the Close method of the SqlDataReader is called. For example, you cannot retrieve output parameters until after you call Close.

Changes made to a result set by another process or thread while data is being read may be visible to the user of the SqlDataReader. However, the precise behavior is timing dependent.

IsClosed and RecordsAffected are the only properties that you can call after the SqlDataReader is closed. Although the RecordsAffected property may be accessed while the SqlDataReader exists, always call Close before returning the value of RecordsAffected to guarantee an accurate return value.

When using sequential access (CommandBehavior.SequentialAccess), an InvalidOperationException will be raised if the SqlDataReader position is advanced and another read operation is attempted on the previous column.

Note

For optimal performance, SqlDataReader avoids creating unnecessary objects or making unnecessary copies of data. Therefore, multiple calls to methods such as GetValue return a reference to the same object. Use caution if you are modifying the underlying value of the objects returned by methods such as GetValue.

Properties

Connection Connection Connection Connection

Gets the SqlConnection associated with the SqlDataReader.

Depth Depth Depth Depth

Gets a value that indicates the depth of nesting for the current row.

FieldCount FieldCount FieldCount FieldCount

Gets the number of columns in the current row.

HasRows HasRows HasRows HasRows

Gets a value that indicates whether the SqlDataReader contains one or more rows.

IsClosed IsClosed IsClosed IsClosed

Retrieves a Boolean value that indicates whether the specified SqlDataReader instance has been closed.

Item[Int32] Item[Int32] Item[Int32] Item[Int32]

Gets the value of the specified column in its native format given the column ordinal.

Item[String] Item[String] Item[String] Item[String]

Gets the value of the specified column in its native format given the column name.

RecordsAffected RecordsAffected RecordsAffected RecordsAffected

Gets the number of rows changed, inserted, or deleted by execution of the Transact-SQL statement.

VisibleFieldCount VisibleFieldCount VisibleFieldCount VisibleFieldCount

Gets the number of fields in the SqlDataReader that are not hidden.

Methods

Close() Close() Close() Close()

Closes the SqlDataReader object.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetBoolean(Int32) GetBoolean(Int32) GetBoolean(Int32) GetBoolean(Int32)

Gets the value of the specified column as a Boolean.

GetByte(Int32) GetByte(Int32) GetByte(Int32) GetByte(Int32)

Gets the value of the specified column as a byte.

GetBytes(Int32, Int64, Byte[], Int32, Int32) GetBytes(Int32, Int64, Byte[], Int32, Int32) GetBytes(Int32, Int64, Byte[], Int32, Int32) GetBytes(Int32, Int64, Byte[], Int32, Int32)

Reads a stream of bytes from the specified column offset into the buffer an array starting at the given buffer offset.

GetChar(Int32) GetChar(Int32) GetChar(Int32) GetChar(Int32)

Gets the value of the specified column as a single character.

GetChars(Int32, Int64, Char[], Int32, Int32) GetChars(Int32, Int64, Char[], Int32, Int32) GetChars(Int32, Int64, Char[], Int32, Int32) GetChars(Int32, Int64, Char[], Int32, Int32)

Reads a stream of characters from the specified column offset into the buffer as an array starting at the given buffer offset.

GetData(Int32) GetData(Int32) GetData(Int32) GetData(Int32)
GetDataTypeName(Int32) GetDataTypeName(Int32) GetDataTypeName(Int32) GetDataTypeName(Int32)

Gets a string representing the data type of the specified column.

GetDateTime(Int32) GetDateTime(Int32) GetDateTime(Int32) GetDateTime(Int32)

Gets the value of the specified column as a DateTime object.

GetDateTimeOffset(Int32) GetDateTimeOffset(Int32) GetDateTimeOffset(Int32) GetDateTimeOffset(Int32)

Retrieves the value of the specified column as a DateTimeOffset object.

GetDecimal(Int32) GetDecimal(Int32) GetDecimal(Int32) GetDecimal(Int32)

Gets the value of the specified column as a Decimal object.

GetDouble(Int32) GetDouble(Int32) GetDouble(Int32) GetDouble(Int32)

Gets the value of the specified column as a double-precision floating point number.

GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

Returns an IEnumerator that iterates through the SqlDataReader.

GetFieldType(Int32) GetFieldType(Int32) GetFieldType(Int32) GetFieldType(Int32)

Gets the Type that is the data type of the object.

GetFieldValue<T>(Int32) GetFieldValue<T>(Int32) GetFieldValue<T>(Int32) GetFieldValue<T>(Int32)

Synchronously gets the value of the specified column as a type. GetFieldValueAsync<T>(Int32, CancellationToken) is the asynchronous version of this method.

GetFieldValueAsync<T>(Int32, CancellationToken) GetFieldValueAsync<T>(Int32, CancellationToken) GetFieldValueAsync<T>(Int32, CancellationToken) GetFieldValueAsync<T>(Int32, CancellationToken)

Asynchronously gets the value of the specified column as a type. GetFieldValue<T>(Int32) is the synchronous version of this method.

GetFloat(Int32) GetFloat(Int32) GetFloat(Int32) GetFloat(Int32)

Gets the value of the specified column as a single-precision floating point number.

GetGuid(Int32) GetGuid(Int32) GetGuid(Int32) GetGuid(Int32)

Gets the value of the specified column as a globally unique identifier (GUID).

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetInt16(Int32) GetInt16(Int32) GetInt16(Int32) GetInt16(Int32)

Gets the value of the specified column as a 16-bit signed integer.

GetInt32(Int32) GetInt32(Int32) GetInt32(Int32) GetInt32(Int32)

Gets the value of the specified column as a 32-bit signed integer.

GetInt64(Int32) GetInt64(Int32) GetInt64(Int32) GetInt64(Int32)

Gets the value of the specified column as a 64-bit signed integer.

GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetName(Int32) GetName(Int32) GetName(Int32) GetName(Int32)

Gets the name of the specified column.

GetOrdinal(String) GetOrdinal(String) GetOrdinal(String) GetOrdinal(String)

Gets the column ordinal, given the name of the column.

GetProviderSpecificFieldType(Int32) GetProviderSpecificFieldType(Int32) GetProviderSpecificFieldType(Int32) GetProviderSpecificFieldType(Int32)

Gets an Object that is a representation of the underlying provider-specific field type.

GetProviderSpecificValue(Int32) GetProviderSpecificValue(Int32) GetProviderSpecificValue(Int32) GetProviderSpecificValue(Int32)

Gets an Object that is a representation of the underlying provider specific value.

GetProviderSpecificValues(Object[]) GetProviderSpecificValues(Object[]) GetProviderSpecificValues(Object[]) GetProviderSpecificValues(Object[])

Gets an array of objects that are a representation of the underlying provider specific values.

GetSchemaTable() GetSchemaTable() GetSchemaTable() GetSchemaTable()

Returns a DataTable that describes the column metadata of the SqlDataReader.

GetSqlBinary(Int32) GetSqlBinary(Int32) GetSqlBinary(Int32) GetSqlBinary(Int32)

Gets the value of the specified column as a SqlBinary.

GetSqlBoolean(Int32) GetSqlBoolean(Int32) GetSqlBoolean(Int32) GetSqlBoolean(Int32)

Gets the value of the specified column as a SqlBoolean.

GetSqlByte(Int32) GetSqlByte(Int32) GetSqlByte(Int32) GetSqlByte(Int32)

Gets the value of the specified column as a SqlByte.

GetSqlBytes(Int32) GetSqlBytes(Int32) GetSqlBytes(Int32) GetSqlBytes(Int32)

Gets the value of the specified column as SqlBytes.

GetSqlChars(Int32) GetSqlChars(Int32) GetSqlChars(Int32) GetSqlChars(Int32)

Gets the value of the specified column as SqlChars.

GetSqlDateTime(Int32) GetSqlDateTime(Int32) GetSqlDateTime(Int32) GetSqlDateTime(Int32)

Gets the value of the specified column as a SqlDateTime.

GetSqlDecimal(Int32) GetSqlDecimal(Int32) GetSqlDecimal(Int32) GetSqlDecimal(Int32)

Gets the value of the specified column as a SqlDecimal.

GetSqlDouble(Int32) GetSqlDouble(Int32) GetSqlDouble(Int32) GetSqlDouble(Int32)

Gets the value of the specified column as a SqlDouble.

GetSqlGuid(Int32) GetSqlGuid(Int32) GetSqlGuid(Int32) GetSqlGuid(Int32)

Gets the value of the specified column as a SqlGuid.

GetSqlInt16(Int32) GetSqlInt16(Int32) GetSqlInt16(Int32) GetSqlInt16(Int32)

Gets the value of the specified column as a SqlInt16.

GetSqlInt32(Int32) GetSqlInt32(Int32) GetSqlInt32(Int32) GetSqlInt32(Int32)

Gets the value of the specified column as a SqlInt32.

GetSqlInt64(Int32) GetSqlInt64(Int32) GetSqlInt64(Int32) GetSqlInt64(Int32)

Gets the value of the specified column as a SqlInt64.

GetSqlMoney(Int32) GetSqlMoney(Int32) GetSqlMoney(Int32) GetSqlMoney(Int32)

Gets the value of the specified column as a SqlMoney.

GetSqlSingle(Int32) GetSqlSingle(Int32) GetSqlSingle(Int32) GetSqlSingle(Int32)

Gets the value of the specified column as a SqlSingle.

GetSqlString(Int32) GetSqlString(Int32) GetSqlString(Int32) GetSqlString(Int32)

Gets the value of the specified column as a SqlString.

GetSqlValue(Int32) GetSqlValue(Int32) GetSqlValue(Int32) GetSqlValue(Int32)

Returns the data value in the specified column as a SQL Server type.

GetSqlValues(Object[]) GetSqlValues(Object[]) GetSqlValues(Object[]) GetSqlValues(Object[])

Fills an array of Object that contains the values for all the columns in the record, expressed as SQL Server types.

GetSqlXml(Int32) GetSqlXml(Int32) GetSqlXml(Int32) GetSqlXml(Int32)

Gets the value of the specified column as an XML value.

GetStream(Int32) GetStream(Int32) GetStream(Int32) GetStream(Int32)

Retrieves binary, image, varbinary, UDT, and variant data types as a Stream.

GetString(Int32) GetString(Int32) GetString(Int32) GetString(Int32)

Gets the value of the specified column as a string.

GetTextReader(Int32) GetTextReader(Int32) GetTextReader(Int32) GetTextReader(Int32)

Retrieves Char, NChar, NText, NVarChar, text, varChar, and Variant data types as a TextReader.

GetTimeSpan(Int32) GetTimeSpan(Int32) GetTimeSpan(Int32) GetTimeSpan(Int32)

Retrieves the value of the specified column as a TimeSpan object.

GetType() GetType() GetType() GetType()

Gets the Type of the current instance.

(Inherited from Object)
GetValue(Int32) GetValue(Int32) GetValue(Int32) GetValue(Int32)

Gets the value of the specified column in its native format.

GetValues(Object[]) GetValues(Object[]) GetValues(Object[]) GetValues(Object[])

Populates an array of objects with the column values of the current row.

GetXmlReader(Int32) GetXmlReader(Int32) GetXmlReader(Int32) GetXmlReader(Int32)

Retrieves data of type XML as an XmlReader.

InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
IsCommandBehavior(CommandBehavior) IsCommandBehavior(CommandBehavior) IsCommandBehavior(CommandBehavior) IsCommandBehavior(CommandBehavior)

Determines whether the specified CommandBehavior matches that of the SqlDataReader .

IsDBNull(Int32) IsDBNull(Int32) IsDBNull(Int32) IsDBNull(Int32)

Gets a value that indicates whether the column contains non-existent or missing values.

IsDBNullAsync(Int32, CancellationToken) IsDBNullAsync(Int32, CancellationToken) IsDBNullAsync(Int32, CancellationToken) IsDBNullAsync(Int32, CancellationToken)

An asynchronous version of IsDBNull(Int32), which gets a value that indicates whether the column contains non-existent or missing values.

The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
NextResult() NextResult() NextResult() NextResult()

Advances the data reader to the next result, when reading the results of batch Transact-SQL statements.

NextResultAsync(CancellationToken) NextResultAsync(CancellationToken) NextResultAsync(CancellationToken) NextResultAsync(CancellationToken)

An asynchronous version of NextResult(), which advances the data reader to the next result, when reading the results of batch Transact-SQL statements.

The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.

Read() Read() Read() Read()

Advances the SqlDataReader to the next record.

ReadAsync(CancellationToken) ReadAsync(CancellationToken) ReadAsync(CancellationToken) ReadAsync(CancellationToken)

An asynchronous version of Read(), which advances the SqlDataReader to the next record.

The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.

ToString() ToString() ToString() ToString()

Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

IDataRecord.GetData(Int32) IDataRecord.GetData(Int32) IDataRecord.GetData(Int32) IDataRecord.GetData(Int32)

Returns an IDataReader for the specified column ordinal.

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()
IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

Applies to