簡體   English   中英

檢查MySQL數據庫連接

[英]Check MySql DB Connection

我想為我的程序創建一個mysql連接檢查器,和往常一樣,我使用了我通常的顧問程序SO ,我着手解決這個問題 ,答案並不完全正確。

問題是:如何在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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM