SqlDataReader SqlDataReader SqlDataReader SqlDataReader Class

定义

提供一种从 SQL Server 数据库中读取只进的行流的方式。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
继承
实现

示例

下面的示例创建SqlConnection、 一个SqlCommand,和一个SqlDataReaderThe following example creates a SqlConnection, a SqlCommand, and a SqlDataReader. 该示例读取数据,将其写到控制台窗口。The example reads through the data, writing it out to the console window. 然后关闭代码SqlDataReaderThe code then closes the SqlDataReader. SqlConnection结束时自动关闭using代码块。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

注解

若要创建SqlDataReader,必须调用ExecuteReader方法的SqlCommand对象,而不是直接使用构造函数。To create a SqlDataReader, you must call the ExecuteReader method of the SqlCommand object, instead of directly using a constructor.

虽然SqlDataReader正在使用中,关联SqlConnection是繁忙的服务SqlDataReader,并可以在执行任何其他操作SqlConnection而不关闭它。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. 这是种情况一直Close方法的SqlDataReader调用。This is the case until the Close method of the SqlDataReader is called. 例如,不能检索输出参数,直到调用后CloseFor example, you cannot retrieve output parameters until after you call Close.

对结果集由另一个进程或线程读取数据时所做的更改可能会对用户可见SqlDataReaderChanges 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.

IsClosedRecordsAffected是后可以调用的唯一属性SqlDataReader已关闭。IsClosed and RecordsAffected are the only properties that you can call after the SqlDataReader is closed. 尽管RecordsAffected可能会访问属性时SqlDataReader存在,始终调用Close返回的值之前RecordsAffected以保证返回精确的值。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.

使用顺序访问时 (CommandBehavior.SequentialAccess)、 一个InvalidOperationException情况下会引发SqlDataReader高级位置和另一个读取上一列上尝试执行操作。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.

备注

为了获得最佳性能,SqlDataReader可避免创建不必要的对象或对其进行不必要的数据副本。For optimal performance, SqlDataReader avoids creating unnecessary objects or making unnecessary copies of data. 因此,多个调用方法如GetValue返回对同一个对象的引用。Therefore, multiple calls to methods such as GetValue return a reference to the same object. 如果您正在修改如由方法返回的对象的基础值要格外小心GetValueUse caution if you are modifying the underlying value of the objects returned by methods such as GetValue.

属性

Connection Connection Connection Connection

获取与 SqlConnection 关联的 SqlDataReaderGets 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

获取一个值,该值指示 SqlDataReader 是否包含一行还是多行。Gets a value that indicates whether the SqlDataReader contains one or more rows.

IsClosed IsClosed IsClosed IsClosed

检索一个布尔值,该值指示是否已关闭指定的 SqlDataReader 实例。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

获取执行 Transact-SQL 语句所更改、插入或删除的行数。Gets the number of rows changed, inserted, or deleted by execution of the Transact-SQL statement.

VisibleFieldCount VisibleFieldCount VisibleFieldCount VisibleFieldCount

获取 SqlDataReader 中未隐藏的字段的数目。Gets the number of fields in the SqlDataReader that are not hidden.

方法

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

关闭 SqlDataReader 对象。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)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)
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.

GetColumnSchema() GetColumnSchema() GetColumnSchema() GetColumnSchema()
GetData(Int32) GetData(Int32) GetData(Int32) GetData(Int32)

返回指定列序号的 IDataReaderReturns an IDataReader for the specified column ordinal.

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)

DateTime 对象的形式获取指定列的值。Gets the value of the specified column as a DateTime object.

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

检索指定列的 DateTimeOffset 对象形式的值。Retrieves the value of the specified column as a DateTimeOffset object.

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

Decimal 对象的形式获取指定列的值。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()

返回循环访问 IEnumeratorSqlDataReaderReturns an IEnumerator that iterates through the SqlDataReader.

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

获取作为对象的数据类型的 TypeGets 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) 是此方法的异步版本。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)是此方法的同步版本。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)

获取指定列的值作为全局唯一标识符 (GUID)。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)

获取指定列的 16 位有符号整数形式的值。Gets the value of the specified column as a 16-bit signed integer.

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

获取指定列的 32 位带符号整数形式的值。Gets the value of the specified column as a 32-bit signed integer.

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

以 64 位有符号整数的形式获取指定列的值。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)

获取一个 Object,它表示基础提供程序特定的字段类型。Gets an Object that is a representation of the underlying provider-specific field type.

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

获取一个表示基础提供程序特定值的 ObjectGets 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()

返回一个 DataTable,它描述 SqlDataReader 的列元数据。Returns a DataTable that describes the column metadata of the SqlDataReader.

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

获取指定列的 SqlBinary 形式的值。Gets the value of the specified column as a SqlBinary.

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

获取指定列的 SqlBoolean 形式的值。Gets the value of the specified column as a SqlBoolean.

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

获取指定列的 SqlByte 形式的值。Gets the value of the specified column as a SqlByte.

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

获取指定列的 SqlBytes 形式的值。Gets the value of the specified column as SqlBytes.

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

获取指定列的 SqlChars 形式的值。Gets the value of the specified column as SqlChars.

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

获取指定列的 SqlDateTime 形式的值。Gets the value of the specified column as a SqlDateTime.

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

获取指定列的 SqlDecimal 形式的值。Gets the value of the specified column as a SqlDecimal.

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

获取指定列的 SqlDouble 形式的值。Gets the value of the specified column as a SqlDouble.

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

获取指定列的 SqlGuid 形式的值。Gets the value of the specified column as a SqlGuid.

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

获取指定列的 SqlInt16 形式的值。Gets the value of the specified column as a SqlInt16.

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

获取指定列的 SqlInt32 形式的值。Gets the value of the specified column as a SqlInt32.

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

获取指定列的 SqlInt64 形式的值。Gets the value of the specified column as a SqlInt64.

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

获取指定列的 SqlMoney 形式的值。Gets the value of the specified column as a SqlMoney.

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

获取指定列的 SqlSingle 形式的值。Gets the value of the specified column as a SqlSingle.

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

获取指定列的 SqlString 形式的值。Gets the value of the specified column as a SqlString.

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

返回指定列中 SQL Server 类型的数据值。Returns the data value in the specified column as a SQL Server type.

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

填充包含记录中所有列的值的 Object 数组,这些值表示为 SQL Server 类型。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)

获取指定列的 XML 值形式的值。Gets the value of the specified column as an XML value.

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

检索作为 Stream 的二进制、图像、varbinary、UDT 和变量数据类型。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)

检索作为 TextReader 的 Char、 NChar、 NText、 NVarChar、 text、 varChar 和 Variant data types。Retrieves Char, NChar, NText, NVarChar, text, varChar, and Variant data types as a TextReader.

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

检索指定列的 TimeSpan 对象形式的值。Retrieves the value of the specified column as a TimeSpan object.

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

获取当前实例的 TypeGets 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)

检索作为 XmlReader 的类型 XML 数据。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)

确定指定的 CommandBehavior 是否与 SqlDataReader 的对应项匹配。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)

IsDBNull(Int32) 的异步版本,其获取指示列是否包含不存在或缺失值的值。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()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

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

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

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

当读取批处理 Transact-SQL 语句的结果时,使数据读取器前进到下一个结果。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)

NextResult() 的异步版本,读取批处理 Transact-SQLTransact-SQL 语句的结果时,将数据读取器推进到下一个结果。An asynchronous version of NextResult(), which advances the data reader to the next result, when reading the results of batch Transact-SQLTransact-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()

SqlDataReader 前进到下一条记录。Advances the SqlDataReader to the next record.

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

Read() 的异步版本,将 SqlDataReader 前移到下一条记录。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)

显式界面实现

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

返回指定列序号的 IDataReaderReturns an IDataReader for the specified column ordinal.

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

释放数据读取器使用的所有资源。Releases all resources that are used by the data reader.

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

返回一个可用于循环访问项集合的枚举数。Returns an enumerator that can be used to iterate through the item collection.

适用于

另请参阅