Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing SqlConnection and SqlCommand c#

In my DAL I write queries like this:

using(SQLConnection conn = "connection string here")
{
    SQLCommand cmd = new ("sql query", conn);
    // execute it blah blah
}

Now it just occurred to me that I am not explicitly closing the SQLCommand object. Now I know the 'using' block will take care of the SQLConnection object, but will this also take care of the SQLCommand object? If not than I have a serious problem. I would have to put in the 'using' on the SQLCommand on thousands and thousands of lines of code or do a cmd.Close() on hundreds of methods. Please tell me that if putting in the using or closing the command will provide a better memory management of the web app?

like image 826
xeshu Avatar asked Jul 30 '10 09:07

xeshu


People also ask

Do you need to close SqlConnection?

If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose . Close and Dispose are functionally equivalent. If the connection pooling value Pooling is set to true or yes , the underlying connection is returned back to the connection pool.

How do I close SqlCommand?

SqlConnection Class Open() : The open() method is used to open the Database connection. Close() : The close() method is used to close the Database connection.

What happens if SqlConnection is not closed?

If you open the connection and don't close it, then it would decrease the connection pools and limits available for connecting to database again. It is always recommended to close the connection and data reader objects explicitly when you use them.

What is SqlConnection and SqlCommand?

A SqlConnection object represents a unique session to a SQL Server data source. With a client/server database system, it is equivalent to a network connection to the server. SqlConnection is used together with SqlDataAdapter and SqlCommand to increase performance when connecting to a Microsoft SQL Server database.


2 Answers

The SqlConnection has no knowledge about the SqlCommand, so you should close it by itself:

using (SqlConnection conn = new SqlConnection("connection string here"))
using (SqlCommand cmd = new SqlCommand("sql query", conn))
{
    // execute it blah blah
}
like image 156
Fredrik Mörk Avatar answered Sep 18 '22 15:09

Fredrik Mörk


No, the using statement will not take care of the command.

You should wrap the commands with using statements as well, since this will properly call Dispose on them:

using(SQLConnection conn = 'connection string here')
{
    using(SQLCommand cmd = new ('sql query', conn))
    {
        //execute it blah blah
    }
}
like image 24
Oded Avatar answered Sep 22 '22 15:09

Oded