SqlDataReader.Read 方法

使 SqlDataReader 前进到下一条记录。

**命名空间:**System.Data.SqlClient
**程序集:**System.Data(在 system.data.dll 中)

语法

声明
Public Overrides Function Read As Boolean
用法
Dim instance As SqlDataReader
Dim returnValue As Boolean

returnValue = instance.Read
public override bool Read ()
public:
virtual bool Read () override
public boolean Read ()
public override function Read () : boolean

返回值

如果存在多个行,则为 true;否则为 false

备注

SqlDataReader 的默认位置在第一条记录前面。因此,必须调用 Read 来开始访问任何数据。

对于每个关联的 SqlConnection,一次只能打开一个 SqlDataReader,在第一个关闭之前,打开另一个的任何尝试都将失败。类似地,在使用 SqlDataReader 时,关联的 SqlConnection 正忙于为它提供服务,直到调用 Close 时为止。

示例

下面的示例创建一个 SqlConnection、一个 SqlCommand 和一个 SqlDataReader。该示例读取全部数据,并将这些数据写到控制台窗口。随后此代码关闭 SqlDataReaderSqlConnectionusing 代码块的结尾处自动关闭。

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()
            Console.WriteLine(String.Format("{0}, {1}", _
                reader(0), reader(1)))
        End While

        ' Call Close when done reading.
        reader.Close()
    End Using
End Sub
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())
        {
            Console.WriteLine(String.Format("{0}, {1}",
                reader[0], reader[1]));
        }

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

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

SqlDataReader 类
SqlDataReader 成员
System.Data.SqlClient 命名空间

其他资源

在 ADO.NET 中连接和检索数据
使用 SQL Server .NET Framework 数据提供程序