SqlDataReader を次のレコードに進めます。
Public Overridable Function Read() As Boolean Implements _ IDataReader.Read
[C#]
public virtual bool Read();
[C++]
public: virtual bool Read();
[JScript]
public function Read() : Boolean;
戻り値
次の行がある場合は true 。それ以外の場合は false 。
実装
解説
SqlDataReader の既定の位置は、最初のレコードの前です。そのため、データへのアクセスを開始するには、 Read を呼び出す必要があります。
関連付けられた SqlConnection で開くことのできる SqlDataReader は、一度に 1 つだけです。データ リーダーを閉じる前に別のデータ リーダーを開くことはできません。同様に、 SqlDataReader の使用中は、関連付けられた SqlConnection は、そのデータ リーダーによって使用されるため、 Close が呼び出されるまではビジー状態になります。
使用例
[Visual Basic, C#, C++] SqlConnection 、 SqlCommand 、および SqlDataReader を作成する例を次に示します。この例では、データを読み取り、コンソールに出力します。最後に、この例では SqlDataReader を閉じてから、 SqlConnection を閉じます。
Public Sub ReadMyData(myConnString As String)
Dim mySelectQuery As String = "SELECT OrderID, CustomerID FROM Orders"
Dim myConnection As New SqlConnection(myConnString)
Dim myCommand As New SqlCommand(mySelectQuery, myConnection)
myConnection.Open()
Dim myReader As SqlDataReader
myReader = myCommand.ExecuteReader()
' Always call Read before accessing data.
While myReader.Read()
Console.WriteLine((myReader.GetInt32(0) & ", " & myReader.GetString(1)))
End While
' always call Close when done reading.
myReader.Close()
' Close the connection when done with it.
myConnection.Close()
End Sub 'ReadMyData
[C#]
public void ReadMyData(string myConnString) {
string mySelectQuery = "SELECT OrderID, CustomerID FROM Orders";
SqlConnection myConnection = new SqlConnection(myConnString);
SqlCommand myCommand = new SqlCommand(mySelectQuery,myConnection);
myConnection.Open();
SqlDataReader myReader;
myReader = myCommand.ExecuteReader();
// Always call Read before accessing data.
while (myReader.Read()) {
Console.WriteLine(myReader.GetInt32(0) + ", " + myReader.GetString(1));
}
// always call Close when done reading.
myReader.Close();
// Close the connection when done with it.
myConnection.Close();
}
[C++]
public:
void ReadMyData(String* myConnString) {
String* mySelectQuery = S"SELECT OrderID, CustomerID FROM Orders";
SqlConnection* myConnection = new SqlConnection(myConnString);
SqlCommand* myCommand = new SqlCommand(mySelectQuery,myConnection);
myConnection->Open();
SqlDataReader* myReader;
myReader = myCommand->ExecuteReader();
// Always call Read before accessing data.
while (myReader->Read()) {
Console::WriteLine(S"{0}, {1}", __box(myReader->GetInt32(0)), myReader->GetString(1));
}
// always call Close when done reading.
myReader->Close();
// Close the connection when done with it.
myConnection->Close();
}
[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン をクリックします。
必要条件
プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ, .NET Compact Framework - Windows CE .NET
参照
SqlDataReader クラス | SqlDataReader メンバ | System.Data.SqlClient 名前空間