Export (0) Print
Expand All

SqlDataReader.Close Method

Closes the SqlDataReader object.

Namespace:  System.Data.SqlClient
Assembly:  System.Data (in System.Data.dll)

public override void Close()



You must explicitly call the Close method when you are through using the SqlDataReader to use the associated SqlConnection for any other purpose.

The Close method fills in the values for output parameters, return values and RecordsAffected, increasing the time that it takes to close a SqlDataReader that was used to process a large or complex query. When the return values and the number of records affected by a query are not significant, the time that it takes to close the SqlDataReader can be reduced by calling the Cancel method of the associated SqlCommand object before calling the Close method.

Caution noteCaution

Do not call Close or Dispose on a Connection, a DataReader, or any other managed object in the Finalize method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a Finalize method in your class definition. For more information, see Garbage Collection.

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);

        SqlDataReader reader = command.ExecuteReader();

        // Call Read before accessing data. 
        while (reader.Read())
                reader[0], reader[1]));

        // Call Close when done reading.

.NET Framework


.NET Framework Client Profile

Supported in: 4, 3.5 SP1



© 2014 Microsoft