检查“MySql数据库连接”

本文关键字:数据库连接 MySql 检查 | 更新日期: 2023-09-27 18:19:07

我想为我的程序创建一个mysql连接检查器,像往常一样,我使用了我通常的顾问SO,我降落在这个问题上,答案不完全正确。

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

检查“MySql数据库连接”

这是我自己的版本检查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;
}