Using SqlConnection

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

Just a simple question is it good to always close a sqlConnection even
if the Connection has been closed by the DataAdapter ?

//Tony
 
Tony Johansson said:
Just a simple question is it good to always close a sqlConnection even
if the Connection has been closed by the DataAdapter ?

It is good to close anything that you open. The DataAdapter closes the
connection if it finds that the connection is in a closed state (so it opens
the connection itself and then closes it). If the DataAdapter finds the
connection already open, it uses the connection and doesn't close it. In
this case _you_ opened the connection, so you should close it.
A good practice is to write the whole thing inside a "using
(SqlConnection ....)" block, so that when the code block is exited the
connection will be automatically Disposed (which will Close it if it is
Open).
 
Hello!

Just a simple question is it good to always close a sqlConnection even
if the Connection has been closed by the DataAdapter ?

//Tony

Hi,

Yes, an ever better approach is to dispose it, like:
using(SqlConnection c = new SqlConnection(...)){
// use the connection
}
in this case you do not have to close it explicitely.
Not only that, but if there is an unhandled exception inside it will
close it too.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top