简体   繁体   中英

Can I attempt to open a MySQL Connection in a catch?

I have this method:

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();
    }
}

However every time it catches an exception, it won't load open the connection because of the current exception caused by the first connection attempt. I am beginning to wonder whether it's because the try/catch is not allowing the program to continue, because there is an unhandled exception in play?

If you really want to use this method, you need to first close your connection before you can use it again.

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();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM