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.
If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With