我有一個程序將用戶項目存儲爲數據庫。當然,程序應該允許用戶根據需要創建和刪除數據庫。當程序啓動時,它會查找特定SQLServer實例中具有該程序所期望的結構的所有數據庫。然後將這些數據庫加載到列表框中,以便用戶可以選擇一個作爲要處理的項目打開。爲什麼有我的數據庫連接打開?
當我嘗試從程序中刪除數據庫時,我總是收到一條SQL錯誤,指出數據庫當前處於打開狀態,操作失敗。我確定檢查要加載的數據庫的代碼導致了這個問題。我不確定爲什麼,因爲我很確定所有的連接都正常關閉。
以下是所有相關功能。調用BuildProjectList後,從ExecuteSQL運行「DROP DATABASE database_name」失敗,並顯示以下消息:「無法刪除數據庫,因爲它當前正在使用」。我正在使用SQLServer 2005.
private SqlConnection databaseConnection;
private string connectionString;
private ArrayList databases;
public ArrayList BuildProjectList()
{
//databases is an ArrayList of all the databases in an instance
if (databases.Count <= 0)
{
return null;
}
ArrayList databaseNames = new ArrayList();
for (int i = 0; i < databases.Count; i++)
{
string db = databases[i].ToString();
connectionString = "Server=localhost\\SQLExpress;Trusted_Connection=True;Database=" + db + ";";
//Check if the database has the table required for the project
string sql = "select * from TableExpectedToExist";
if (ExecuteSQL(sql)) {
databaseNames.Add(db);
}
}
return databaseNames;
}
private bool ExecuteSQL(string sql)
{
bool success = false;
openConnection();
SqlCommand cmd = new SqlCommand(sql, databaseConnection);
try
{
cmd.ExecuteNonQuery();
success = true;
}
catch (SqlException ae)
{
MessageBox.Show(ae.Message.ToString());
}
closeConnection();
return success;
}
public void openConnection()
{
databaseConnection = new SqlConnection(connectionString);
try
{
databaseConnection.Open();
}
catch(Exception e)
{
MessageBox.Show(e.ToString(), "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void closeConnection()
{
if (databaseConnection != null)
{
try
{
databaseConnection.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
我找不到SQLConnection.Pooling屬性,但我在刪除數據庫之前嘗試調用SQLConnection.ClearAllPools(),並且執行了該操作。謝謝! – Everett 2010-06-06 02:23:43