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

Jaq*_*ues 6 c# sql-server sqlconnection

我指的是很久很久以前发布在Stack Overflow上的帖子. 结束使用关闭打开的SQL连接

但是我有一个问题.我发现在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();
                        }
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 14

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

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