SqlDataReader.Read 方法

定义

SqlDataReader 前进到下一条记录。

public:
 override bool Read();
public:
 virtual bool Read();
public override bool Read ();
public bool Read ();
override this.Read : unit -> bool
abstract member Read : unit -> bool
override this.Read : unit -> bool
Public Overrides Function Read () As Boolean
Public Function Read () As Boolean

返回

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

实现

例外

执行命令文本时,SQL Server 返回了一个错误。

示例

以下示例创建 SqlConnectionSqlCommandSqlDataReader。 该示例通读数据,将其写入控制台窗口。 然后,代码关闭 SqlDataReader。 在 SqlConnection 代码块末尾 using 自动关闭 。

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 dataRecord)
{
    Console.WriteLine(String.Format("{0}, {1}", dataRecord[0], dataRecord[1]));
}
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

注解

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

每个关联的SqlConnection一次只能打开一SqlDataReader个,任何打开另一个的尝试都将失败,直到第一个尝试关闭。 同样,在使用 时 SqlDataReader ,关联的 SqlConnection 将忙于提供它,直到调用 Close

适用于

另请参阅