SqlDataReader 类

定义

提供一种从 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
继承
SqlDataReader
实现

示例

下面的示例创建 SqlConnectionSqlCommandSqlDataReaderThe 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. SqlConnectionusing 代码块的末尾自动关闭。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,必须调用 SqlCommand 对象的 ExecuteReader 方法,而不是直接使用构造函数。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. 在调用 SqlDataReaderClose 方法之前,会出现这种情况。This is the case until the Close method of the SqlDataReader is called. 例如,在调用 Close之后,才能检索输出参数。For example, you cannot retrieve output parameters until after you call Close.

在读取数据时,由其他进程或线程对结果集所做的更改可能对 SqlDataReader的用户可见。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.

IsClosedRecordsAffected 是关闭 SqlDataReader 后可调用的唯一属性。IsClosed and RecordsAffected are the only properties that you can call after the SqlDataReader is closed. 虽然 SqlDataReader 存在时可以访问 RecordsAffected 属性,但在返回 RecordsAffected 值之前始终调用 Close,以保证准确的返回值。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)时,如果 SqlDataReader 位置是高级的,并且对上一列尝试另一次读取操作,则将引发 InvalidOperationExceptionWhen 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. 如果要修改 GetValue等方法返回的对象的基础值,请务必小心。Use caution if you are modifying the underlying value of the objects returned by methods such as GetValue.

属性

Connection

获取与 SqlConnection 关联的 SqlDataReaderGets the SqlConnection associated with the SqlDataReader.

Depth

获取一个值,用于指示当前行的嵌套深度。Gets a value that indicates the depth of nesting for the current row.

FieldCount

获取当前行中的列数。Gets the number of columns in the current row.

HasRows

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

IsClosed

检索一个布尔值,该值指示是否已关闭指定的 SqlDataReader 实例。Retrieves a Boolean value that indicates whether the specified SqlDataReader instance has been closed.

Item[Int32]

在给定列序号的情况下,获取指定列的以本机格式表示的值。Gets the value of the specified column in its native format given the column ordinal.

Item[String]

在给定列名称的情况下,获取指定列的以本机格式表示的值。Gets the value of the specified column in its native format given the column name.

RecordsAffected

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

VisibleFieldCount

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

方法

Close()

关闭 SqlDataReader 对象。Closes the SqlDataReader object.

CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(继承自 MarshalByRefObject)
Dispose(Boolean)

释放由 SqlDataReader 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the SqlDataReader and optionally releases the managed resources.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetBoolean(Int32)

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

GetByte(Int32)

以字节的形式获取指定列的值。Gets the value of the specified column as a byte.

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)

以单个字符的形式获取指定列的值。Gets the value of the specified column as a single character.

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()

获取只读列架构集合。Gets the read-only column schema collection.

GetData(Int32)

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

GetDataTypeName(Int32)

获取一个表示指定列的数据类型的字符串。Gets a string representing the data type of the specified column.

GetDateTime(Int32)

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

GetDateTimeOffset(Int32)

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

GetDecimal(Int32)

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

GetDouble(Int32)

以双精度浮点数字的形式获取指定列的值。Gets the value of the specified column as a double-precision floating point number.

GetEnumerator()

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

GetFieldType(Int32)

获取作为对象的数据类型的 TypeGets the Type that is the data type of the object.

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)

异步获取作为类型的指定列的值。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)

以单精度浮点数字的形式获取指定列的值。Gets the value of the specified column as a single-precision floating point number.

GetGuid(Int32)

获取指定列的值作为全局唯一标识符 (GUID)。Gets the value of the specified column as a globally unique identifier (GUID).

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetInt16(Int32)

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

GetInt32(Int32)

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

GetInt64(Int32)

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

GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(继承自 MarshalByRefObject)
GetName(Int32)

获取指定列的名称。Gets the name of the specified column.

GetOrdinal(String)

在给定列名时获取相应的列序号。Gets the column ordinal, given the name of the column.

GetProviderSpecificFieldType(Int32)

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

GetProviderSpecificValue(Int32)

获取一个表示基础提供程序特定值的 ObjectGets an Object that is a representation of the underlying provider specific value.

GetProviderSpecificValues(Object[])

获取表示基础提供程序特定值的对象的数组。Gets an array of objects that are a representation of the underlying provider specific values.

GetSchemaTable()

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

GetSqlBinary(Int32)

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

GetSqlBoolean(Int32)

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

GetSqlByte(Int32)

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

GetSqlBytes(Int32)

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

GetSqlChars(Int32)

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

GetSqlDateTime(Int32)

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

GetSqlDecimal(Int32)

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

GetSqlDouble(Int32)

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

GetSqlGuid(Int32)

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

GetSqlInt16(Int32)

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

GetSqlInt32(Int32)

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

GetSqlInt64(Int32)

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

GetSqlMoney(Int32)

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

GetSqlSingle(Int32)

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

GetSqlString(Int32)

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

GetSqlValue(Int32)

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

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)

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

GetStream(Int32)

检索作为 Stream 的二进制、图像、varbinary、UDT 和变量数据类型。Retrieves binary, image, varbinary, UDT, and variant data types as a Stream.

GetString(Int32)

获取指定列的字符串形式的值。Gets the value of the specified column as a string.

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)

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

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
GetValue(Int32)

获取指定列以本机格式表示的值。Gets the value of the specified column in its native format.

GetValues(Object[])

使用当前行的列值来填充对象数组。Populates an array of objects with the column values of the current row.

GetXmlReader(Int32)

检索作为 XmlReader 的类型 XML 数据。Retrieves data of type XML as an XmlReader.

InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(继承自 MarshalByRefObject)
IsCommandBehavior(CommandBehavior)

确定指定的 CommandBehavior 是否与 SqlDataReader 的对应项匹配。Determines whether the specified CommandBehavior matches that of the SqlDataReader .

IsDBNull(Int32)

获取一个值,该值指示列中是否包含不存在的或缺少的值。Gets a value that indicates whether the column contains non-existent or missing values.

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()

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

(继承自 Object)
MemberwiseClone(Boolean)

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

(继承自 MarshalByRefObject)
NextResult()

当读取批处理 Transact-SQL 语句的结果时,使数据读取器前进到下一个结果。Advances the data reader to the next result, when reading the results of batch Transact-SQL statements.

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()

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

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()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)

显式界面实现

IDataRecord.GetData(Int32)

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

IDisposable.Dispose()

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

IEnumerable.GetEnumerator()

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

适用于

另请参阅