System.Data.SqlClient Namespace SqlDataReader Class
Advances the data reader to the next record.
[ VB ]
NotOverridable Public Function Read ( ) As Boolean
[ C# ]
public bool Read ( );
[ C++ ]
public: __sealed bool Read ( );
[ JScript ]
public function Read ( ) : Boolean
true if another record could be read; otherwise, false.
The default positioning is prior to the first record, therefore you must call Read before 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 in use, the associated SqlConnection is busy serving the data until you call Close.
The following example initializes an SqlConnection, an SqlCommand, and an SqlDataReader. The example reads through the data, writing each row of data to the page, then closes the reader and the connection.
void ReadMyData ( string connString ) {
string query = "SELECT OrderID, Customer FROM Orders";
SqlConnection myConn = new SqlConnection ( connString );
SqlCommand myCommand = new SqlCommand ( query, myConn );
myConn.Open ( );
SqlDataReader myReader = myCommand.ExecuteReader ( );
try {
// loop thru the reader.
while ( myReader.Read ( ) ) {
Response.Write ( myReader.GetInt32 ( 0 ) +
", " + myReader.GetString ( 1 ) );
}
}
finally {
// always close the reader when done.
myReader.Close ( );
// always close the connection when done.
myConn.Close ( );
}
}
Public Sub ReadMyData ( connString As String )
Dim query As String = "SELECT OrderID, Customer FROM Orders"
Dim myConn As New SqlConnection ( connString )
Dim myCommand As New SqlCommand ( query, myConn )
myConn.Open ( )
Dim myReader As SqlDataReader = myCommand.ExecuteReader ( )
Try
// loop thru the reader.
While myReader.Read ( )
Response.Write ( ( myReader.GetInt32 ( 0 ).ToString & _
", " & myReader.GetString ( 1 ) ) )
End While
Finally
' always close the reader when done.
myReader.Close ( )
' always close the connection when done.
myConn.Close ( )
End Try
End Sub |
|
C# |
VB |
SqlDataReader Members