我要翻译的内容是:
我参考了很久以前在Stack Overflow上发布的一篇文章。 Does End Using close an open SQL Connection
然而,我有一个问题。 我发现在SQL 2012 Express版和SQL 2008 Developer Edition上使用using根本不关闭连接。
这是我使用的代码。 该代码将遍历每个数据库并查找指定的特定表,但是,当它完成时,并且您在服务器上运行sp_who时,所有连接仍然存在。 状态为睡眠状态,cmd为“等待命令”,但是当您尝试创建数据库时,模型无法锁定,因为您仍然有一个打开的连接。 这是类中的错误吗?
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
块周围的{ }
来合并using
块,这样可以节省一些缩进... - Mark Rotteveel