我指的是很久很久以前发布在Stack Overflow上的帖子.
Does End Using close an open SQL Connection
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(); } } } } } } }@H_502_9@