แก้ไข

แชร์ผ่าน


SqlDataReader.Read Method

Definition

Advances the SqlDataReader to the next record.

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

Returns

true if there are more rows; otherwise false.

Implements

Exceptions

SQL Server returned an error while executing the command text.

Examples

The following example creates a SqlConnection, a SqlCommand, and a SqlDataReader. The example reads through the data, writing it out to the console window. The code then closes the SqlDataReader. The SqlConnection is closed automatically at the end of the using code block.

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

Remarks

The default position of the SqlDataReader is before the first record. Therefore, you must call Read to begin accessing any data.

Only one SqlDataReader per associated SqlConnection may be open at a time, and any attempt to open another will fail until the first one is closed. Similarly, while the SqlDataReader is being used, the associated SqlConnection is busy serving it until you call Close.

Applies to

See also