2010-06-06 89 views
0

我有一個程序將用戶項目存儲爲數據庫。當然,程序應該允許用戶根據需要創建和刪除數據庫。當程序啓動時,它會查找特定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); 
     } 
    } 
} 

回答

2

SqlConnection類輪詢實際的數據庫連接。如果關閉SqlConnection,連接將返回到連接池。要防止此行爲,請設置SqlConnection.Pooling = false;

編輯

約翰似乎是更重要的一點在這裏。但是,您也可能不得不繼續進行投票。

+0

我找不到SQLConnection.Pooling屬性,但我在刪除數據庫之前嘗試調用SQLConnection.ClearAllPools(),並且執行了該操作。謝謝! – Everett 2010-06-06 02:23:43

2

兩個註釋。首先,你應該使用使用聲明,你的可能會更清潔。

更多關於主題,當您嘗試刪除它時,您正在連接到數據庫!改爲連接到主數據庫。

+0

我不是那個問題。我試圖在刪除它之前連接到主數據庫,並沒有解決任何問題。它的工作原理是如果不調用BuildProjectList。 – Everett 2010-06-06 02:19:18

相關問題