SqlDataReader.Close Method

Definition

Closes the SqlDataReader object.

public:
 override void Close();
public override void Close ();
override this.Close : unit -> unit
Public Overrides Sub Close ()

Implements

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.

using Microsoft.Data.SqlClient;

class Program
{
    static void Main()
    {
        string str = "Data Source=(local);Initial Catalog=Northwind;"
            + "Integrated Security=SSPI";
        ReadOrderData(str);
    }
    private static void ReadOrderData(string connectionString)
    {
        string queryString =
            "SELECT OrderID, CustomerID FROM dbo.Orders;";

        using (SqlConnection connection =
                   new SqlConnection(connectionString))
        {
            connection.Open();

            using (SqlCommand command =
                new SqlCommand(queryString, connection))
            {
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    // Call Read before accessing data.
                    while (reader.Read())
                    {
                        Console.WriteLine(String.Format("{0}, {1}",
                            reader[0], reader[1]));
                    }

                    // Call Close when done reading.
                    reader.Close();
                }
            }
        }
    }
}

Remarks

You must ensure the Close method is called when you are through using the SqlDataReader before using the associated SqlConnection for any other purpose. The Close method may either be called directly or through the Dispose method, disposing directly or in the context of the using statement block.

The Close method populates the values for output parameters, return values and RecordsAffected on the SqlDataReader by consuming any pending results. This may be a long operation depending on the amount of data to be consumed. If output values, return values, and RecordsAffected are not important to your application, the time to close may be shortened by calling the Cancel method of the associated SqlCommand object before the Close method is called.

Caution

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.

Applies to