Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to ensure a SQL connection is closed when an exception is thrown?

I use a pattern that looks something like this often. I'm wondering if this is alright or if there is a best practice that I am not applying here.

Specifically I'm wondering; in the case that an exception is thrown is the code that I have in the finally block enough to ensure that the connection is closed appropriately?

public class SomeDataClass : IDisposable
{
    private SqlConnection _conn;

    //constructors and methods

    private DoSomethingWithTheSqlConnection()
    {
        //some code excluded for brevity

        try
        {
            using (SqlCommand cmd = new SqlCommand(SqlQuery.CountSomething, _SqlConnection))
            {
                _SqlConnection.Open();
                countOfSomething = Convert.ToInt32(cmd.ExecuteScalar());
            }
        }
        finally
        {
            //is this the best way?
            if (_SqlConnection.State == ConnectionState.Closed)
                _SqlConnection.Close();
        }

        //some code excluded for brevity
    }

    public Dispose()
    {
        _conn.Dispose();
    }
}
like image 459
Eric Schoonover Avatar asked Sep 26 '08 18:09

Eric Schoonover


People also ask

How do I close an exception connection?

You must explicitly close the connection by calling Close or Dispose." In your first example you do not "explicitly close the connection". When using the using statement, it calls Dispose method on the object being used, which in turn would call Close method, in case of SqlCeConnection .

Which exception is thrown when connection object is closed?

SQLException: Invalid state, the Connection object is closed.

What happens when SQL connection is closed?

If connection pooling is off, the transaction is rolled back after SqlConnection. Close is called. Transactions started through System. Transactions are controlled through the System.

Why should you make sure you always close out your database connection?

If you do not close your database connections, many problems can occur like web pages hanging, slow page loads, and more. Think of it as going through a door to your house. Maybe the door will shut by itself, but maybe it won't. If it doesn't shut, who knows what will happen.


1 Answers

Wrap your database handling code inside a "using"

using (SqlConnection conn = new SqlConnection (...))
{
    // Whatever happens in here, the connection is 
    // disposed of (closed) at the end.
}
like image 181
Sklivvz Avatar answered Oct 18 '22 18:10

Sklivvz