I'm referring to a post that was put on Stack Overflow a long, long time ago. Does End Using close an open SQL Connection
I have a problem however. I found that using does not close the connection at all on SQL 2012 Express edition as well as SQL 2008 Developer Edition.
Here is the code that I've used. The code will go through each Database and look for a specific table specified, however, when it is done, and you run an sp_who on the server, all the connections are still there. The status is sleeping and the cmd is "AWAITING COMMAND" but when you try to create a database for instance, model cannot be locked, because you still have a connection open to it. Is this a bug in the class?
using (SqlConnection conn = new SqlConnection("Data Source=" + ServerNameCombo.Text + ";Initial Catalog=master;Persist Security Info=True;User ID=" + UserNameEdit.Text + ";Password=" + PasswordEdit.Text))
{
using (SqlCommand dbs = new SqlCommand("Select name from sysdatabases", conn))
{
conn.Open();
using (SqlDataReader reader = dbs.ExecuteReader())
{
while (reader.Read())
{
using (SqlConnection dbconn = new SqlConnection("Data Source=" + ServerNameCombo.Text + ";Initial Catalog=" + reader["name"].ToString() + ";Persist Security Info=True;User ID=" + UserNameEdit.Text + ";Password=" + PasswordEdit.Text))
{
using (SqlCommand dbscmd = new SqlCommand("Select name from sysobjects where name = '" + TableName + "'", dbconn))
{
dbconn.Open();
if (dbscmd.ExecuteScalar() != null)
{
DBNames += (DBNames != "" ? "," : "") + reader["name"].ToString();
}
}
}
}
}
}
}
using
-blocks by removing the{ }
around anotherusing
-block, might save some indentation... – Knowhow