System.Data.SqlClient Namespace SqlDataReader Class
Closes the data reader object.
[ VB ]
NotOverridable Public Sub Close ( )
[ C# ]
void Close ( );
[ C++ ]
public: __sealed void Close ( );
[ JScript ]
public function Close ( );
The Close method must be called when finished with the data reader.
While the data reader is in use, the associated connection is busy serving the data reader. This will be the case until Close is called.
Close fills in the values for output parameters, return values and RecordsAffected, increasing the amount of time it takes to close an SqlDataReader that was used to process a large or complicated query.
In cases where the return values and the number of records affected by a query are not significant, the amount of time it takes to close the SqlDataReader can be reduced by calling the Cancel method of the associated SqlCommand object before calling the Close method.
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