2014-11-03 68 views
0

我有這樣的方法:我可以嘗試在catch中打開MySQL連接嗎?

static void DbConnect() 
{ 
    // Connects to the Db using a simplified Connection string. 
    try 
    { 
     mySqlConnect = new MySqlConnection("server=" + Setup_Controller.server + ";uid=root;"); 
     mySqlConnect.Open(); 
    } 
    // If a password is required, tries again using the password provided. 
    catch (MySqlException) 
    { 
     mySqlConnect = new MySqlConnection("server=" + Setup_Controller.server + ";uid=root;password='" + Setup_Controller.password + "';"); 
     mySqlConnect.Open(); 
    } 
} 

但是每次捕獲異常時,它不會加載打開,因爲所造成的第一次嘗試連接當前異常的連接。我開始懷疑這是因爲try/catch不允許程序繼續運行,因爲在運行中存在未處理的異常?

+0

後你得到異常的詳細信息。 – 2014-11-03 04:35:49

+0

如果第二次連接嘗試失敗,您希望發生什麼? – 2014-11-03 04:36:46

+0

@RiciculatedSpline「無法連接到任何指定的MySQL主機」。我相信這是因爲MySQL連接需要密碼,這就是第一次連接失敗的原因。 – Ben 2014-11-03 04:46:53

回答

0

如果您確實想使用此方法,則需要先關閉連接,然後才能再次使用它。

static void DbConnect() 
{ 
    // Connects to the Db using a simplified Connection string. 

    try 
    { 
     mySqlConnect = new MySqlConnection("server=" + Setup_Controller.server + 
     ";uid=root;"); 
     mySqlConnect.Open(); 
    } 
// If a password is required, tries again using the password provided. 
catch (MySqlException) 
{ 

     //make sure connection is close 
    if(mySqlConnection != null) 
      mySqlConnect.Close(); 
} 
/* i don't know what this class looks like but most data class expose some method 
    to see if the connection is still open or close. If there is not an IsOpen check 
    for IsClose or something like this 
*/ 
if(!mySqlConnect.IsOpen()) 
{ 
    try 
    { 

     mySqlConnect = new MySqlConnection("server=" + Setup_Controller.server + 
     ";uid=root;password='" + Setup_Controller.password + "';"); 
     mySqlConnect.Open(); 
    } 
    catch (MySqlException) 
    { 
     //make sure connection is close 
     mySqlConnect.Close(); 
    } 

}

+0

當它打開失敗時,你是否真的需要關閉它(即open調用引發異常)?不是不可能的,但對我來說聽起來很奇怪。 – 2014-11-03 05:32:19

+0

這絕對看起來像一個更堅實的編程解決方案。 :)只是一個問題,你*爲什麼*第二個連接不想打開(在我的原始示例中)? – Ben 2014-11-03 05:41:35

+0

我唯一的猜測是第二個連接也會拋出一個錯誤。 – jsdev 2014-11-03 05:58:39