Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ado.net Closing Connection when using "using" statement

Tags:

c#

tsql

ado.net

I am doing my database access methods to SQL Server like this

  using (SqlConnection con = new SqlConnection(//connection string)   {     using (SqlCommand cmd = new SqlCommand(storedProcname, con))      {        try{            con.open();            //data reader code        }        catch        {         }      }   } 

Do I need to be closing or disposing of SqlCommand, or will the using statement take care of that for me? I just don't want connection hanging open Thanks

like image 352
twal Avatar asked Dec 08 '10 16:12

twal


People also ask

What does Conn close () do?

The close() operation closes the connection--it doesn't do anything to the connection reference. You might not be able to do anything with the connection, but it's not null.

Does disposing SqlConnection close 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 . 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.

Do SQL connections close automatically?

If the application ends, the connection gets closed, along with everything else that was opened.

Will using statement close connection?

CloseConnection to close your Connection object automatically when your DataReader closes. (Thanks for the lead in Wolfgang!) The using statement will close all of your objects and dispose of them for you. This is one of my personal favorites as it can make development a lot easier.


1 Answers

The using will take care of it for you. Under the hood, SqlConnection.Dispose() calls the SqlConnection.Close() method, and SqlCommand.Dispose() calls SqlCommand.Close().

As additional background, a using statement is syntactic sugar for a try ... finally that disposes the IDisposable object in the finally.

like image 146
Phil Hunt Avatar answered Oct 21 '22 13:10

Phil Hunt