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 於執行命令文字時傳回錯誤。

範例

下列範例會建立 SqlConnection、、 SqlCommandSqlDataReader。 此範例會讀取數據,並將它寫出主控台視窗。 然後程式代碼會 SqlDataReader關閉 。 會在 SqlConnection 程式代碼區塊結尾 using 自動關閉 。

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 dataRecord)
    {
        Console.WriteLine(String.Format("{0}, {1}", dataRecord[0], dataRecord[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 是在第一筆記錄之前。 因此,您必須呼叫 Read 以開始存取任何數據。

每個相關聯的SqlConnection一次只能開啟一個SqlDataReader,而且任何嘗試開啟另一個的嘗試都會失敗,直到第一次關閉為止。 同樣地,在使用 時 SqlDataReader ,相關聯的 SqlConnection 會忙於提供服務,直到您呼叫 Close為止。

適用於

另請參閱