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?
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.
SqlConnection Class Open() : The open() method is used to open the Database connection. Close() : The close() method is used to close the Database connection.
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.
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.
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
}
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
}
}
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