“using”关键字不会关闭打开的SQL连接

时间:2013-11-25 20:55:20

标签: c# sql-server sqlconnection

我指的是很久很久以前发布在Stack Overflow上的帖子。 Does End Using close an open SQL Connection

然而,我有一个问题。我发现在SQL 2012 Express Edition以及SQL 2008 Developer Edition上使用不会完全关闭连接。

这是我用过的代码。代码将遍历每个数据库并查找指定的特定表,但是,当它完成后,并且在服务器上运行sp_who时,所有连接仍然存在。状态为休眠状态,cmd为“AWAITING COMMAND”,但是当您尝试创建数据库时,无法锁定模型,因为您仍然可以打开连接。这是课堂上的一个错误吗?

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();
                        }
                    }
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:14)

这是预期的行为;它会关闭托管连接,这意味着它会释放底层连接 连接池。这样可以人为地保持连接打开,以便相同连接字符串和标识的下一个受管连接可以使用现有连接(设置TDS管道中的重置位)以避免连接启动延迟。

如果您不想这样做:在连接字符串(Pooling=false)中禁用连接池。

相关问题