Search code examples
sql-serverado.netsqldatareadersqlconnection

SqlDataReader Close and SqlConnection


What happens with the connection in this case? I don't know if reader.Close() close the open sqlconnection.

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);
        connection.Open();

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

Solution

  • Closing the reader will not alter the state of the connection. If you did want to do this you can pass CommandBehavior.CloseConnection to the ExecuteReader method of the SqlCommand instance.

    SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
    

    It is recommended you put a using block around all your disposable types like your SqlDataReader instance.

    using(SqlDataReader reader = command.ExecuteReader()) {
      // rest of code
    }
    

    See also CommandBehavior for more options.