Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to close SQL Server connection with the using keyword?

I keep finding conflicting results for this question. Let's look at this C# code of running an SQL query:

using (SqlConnection cn = new SqlConnection(strConnectString))
{
    cn.Open();

    using (SqlCommand cmd = new SqlCommand(strSQL, cn))
    {
        cmd.ExecuteNonQuery();
    }

    //Do I need to call?
    cn.Close();
}

Do I need to call that last cn.Close()? The reason I'm asking is that in a heavy traffic web app I run out of connections in a pool.

like image 674
c00000fd Avatar asked Mar 21 '13 02:03

c00000fd


People also ask

Is it necessary to close SQL connection?

If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose .

What happens if I dont close SQL connection?

Not closing connections could cause timeouts as the connection pool may run out of available connections that can be used. A side point to this. If you use the using keyword, that will automatically close the connection for you.

How do I stop a SQL Server connection?

Connection 2: Connect to SQL Server and open a new query window, but do not execute a query. We will execute a query in this connection later. Now pause SQL Server by right clicking on the server instance and selecting Pause. It opens up a pop-up window to confirm or cancel the pause operation.

Why database connections must be closed?

For the purpose of safe coding, you should always close database connections explicitly to make sure that the code was able to close itself gracefully and to prevent any other objects from reusing the same connection after you are done with it.


1 Answers

The using keyword as used here:

using (SqlConnection cn = new SqlConnection(strConnectString))
{
    // Stuff
}

is short for:

SqlConnection cn = null;
try
{
    cn = new SqlConnection(strConnectString);
    // Stuff
}
finally
{
    if (cn != null) cn.Dispose();
}

cn.Dispose() will be called immediately after cn goes out of scope of the using, which in turn immediately closes the connection (because SqlConnection.Dispose() does just that).

UPDATE

This should not be confused with garbage collection. GC is non-deterministic in .NET, which is exactly why the IDisposable inteface and Dispose Pattern were introduced. IDisposable allows expensive resources to be released in a timely, deterministic manner.

like image 88
Eric J. Avatar answered Oct 05 '22 15:10

Eric J.