2

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

3 Answers 3

3

reader.Close() won't close the SqlConnection, but since you have a using statement, once you exit the using block the connection will get closed anyway.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

Check Connection State

if(connection.State == ConnectionState.Open)
{
    connection.Close();
}
connection.Open();

And since you are doing

using (SqlConnection connection =
               new SqlConnection(connectionString))
    {

this will make sure connection is disposed as it inherits from IDisposable despite Exception. And object are disposed once they exit their corresponding scope.

And better use

using(SqlCommand command = new SqlCommand(queryString, connection))

and

using(SqlDataReader reader = command.ExecuteReader())

for the same reason mentioned above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.