Does "using" automatically close SqlConnection

  • Thread starter Thread starter John Bailo
  • Start date Start date
J

John Bailo

using (
SqlCommand cmd = new SqlCommand("select * sample"),
new SqlConnection( sqlDsn )
)
)

{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
}

Does the SqlConnection automatically get closed when I exit the using?
 
In your specific scenario the SqlConnection will be closed but not by the
using statement. The SqlCommand will close the SqlConnection when it is
disposed by the using statement.
The SqlCommand will only close the SqlConnection if it opened the connection
itself. So if the connection was already open before it was passed as a
parameter to the SqlCommand it will not be closed by the SqlCommand.

Sandor
 

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