2

我想为我的程序创建一个 mysql 连接检查器,并且像往常一样,我使用了我常用的顾问SO,我遇到了这个问题,但答案并不完全正确。

问题是: 如何在 c# 中检查有效的 mysql 连接?

4

1 回答 1

8

这是我自己检查mysql连接的版本。

public static bool checkDB_Conn()
{
    var conn_info = "Server=address;Port=3306;Database=dbhere;Uid=admin;Pwd=123";
    bool isConn = false;
    MySqlConnection conn = null;
    try
    {
        conn = new MySqlConnection(conn_info);
        conn.Open();
        isConn = true;
    }
    catch (ArgumentException a_ex)
    {
        /*
        Console.WriteLine("Check the Connection String.");
        Console.WriteLine(a_ex.Message);
        Console.WriteLine(a_ex.ToString());
        */
    }
    catch (MySqlException ex)
    {
        /*string sqlErrorMessage = "Message: " + ex.Message + "\n" +
        "Source: " + ex.Source + "\n" +
        "Number: " + ex.Number;
        Console.WriteLine(sqlErrorMessage);
        */
        isConn = false;
        switch (ex.Number)
        {
            //http://dev.mysql.com/doc/refman/5.0/en/error-messages-server.html
            case 1042: // Unable to connect to any of the specified MySQL hosts (Check Server,Port)
                break;
            case 0: // Access denied (Check DB name,username,password)
                break;
            default:
                break;
        }
    }
    finally
    {
        if (conn.State == ConnectionState.Open)
        {
            conn.Close();
        }
    }
    return isConn;
}
于 2013-06-19T15:25:32.577 回答