3

I wanted to create a mysql connection checker for my program and as always i used my usual advisor SO and i landed on this Question and the answer was not exactly right.

The Question is: How to check for a valid mysql connection at c#?

1 Answer 1

8

Here is my own version to check mysql connection.

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

You should use using instead of finally.
Yes i didnt know that "using" was closing the connection. Thanks
compying this code to my project error says : The name 'ConnectionState' does not exist in the current context. both using MySql.Data; using MySql.Data.MySqlClient; are present...
System.Data.ConnectionState.Open is the full path

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.