【问题标题】:Check MySql DB Connection检查 MySql 数据库连接
【发布时间】:2013-06-19 15:25:32
【问题描述】:

我想为我的程序创建一个 mysql 连接检查器,并且一如既往地使用我常用的顾问 SO,然后我登陆了这个 Question,但答案并不完全正确。

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

【问题讨论】:

    标签: c# mysql database-connection


    【解决方案1】:

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

    【讨论】:

    • 您应该使用using 而不是finally
    • 是的,我不知道“使用”正在关闭连接。谢谢
    • 将此代码编译到我的项目错误中说:当前上下文中不存在名称“ConnectionState”。都使用 MySql.Data;使用 MySql.Data.MySqlClient;存在...
    • System.Data.ConnectionState.Open 是完整路径
    猜你喜欢
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多