2014-11-03 65 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