Stopbyte

How to Test Connection to MySQL database using C#?

Hi,
how to check connection to MySQL database? And see if it’s connected or not!

2 Likes

That’s quite easy i guess, You can just connect the normal way to MySql Database within a try...catch block and see if it fails or not!

here is a simple method i developed:

public bool CheckMySqlConnection(string ConnectionString)
{
    bool failed = false;
    MySqlConnection conx = null;

    try
    {
        using (conx = new MySqlConnection(ConnectionString))
        {
            conx.Open();
            /* If we reached here, that means the connection to the database was successful. */
            return true;
        }
    }
    catch (Exception ex)
    {
        // We are here that means the connection failed!
        // You can handle the exception differently if you want to provide richer error handling.
        // At this moment we just return "false" which means the connection failed.
        return false;
    }
}

Notice: that i used the using block, to make sure that the Connection is closed & disposed once done with it!

I think you can do it like this:

private void ButtonForCheck(object sender, EventArgs e) //create button for check
{
    try
    {            
        string serverName = address; // Address server (for local database "localhost")
        string userName = name;  // user name
        string dbName = basename; //Name database
        string port =  "3306"; // Port for connection
        string password = password; // Password for connection 
        string conStr = "server=" + serverName +
                   ";user=" + userName +
                   ";database=" + dbName +
                   ";port=" + port +
                   ";password=" + password + ";";

        using (MySqlConnection con = new MySqlConnection(conStr))
        {
            string sql0="SELECT @@IDENTITY"; //any request for cheking
            MySqlCommand cmd0 = new MySqlCommand(sql0, con);
            con.Open();
            cmd0.ExecuteScalar();

            label11.Text = "Connection True"; // label 
            con.Close();
        }
    }
    catch (Exception)
    {
        label11.Text = "Connection False";
    }
}
1 Like

Your code always give true, because you can not use SqlConnection or MySqlConnection

1 Like

Well… @ivan.norin if it returns true then it has successfully connected which is exactly what you mentioned in your question, otherwise if you needed some different behavior you had to specify! :stuck_out_tongue_winking_eye:

Yes, your example can be used as a template,
hahahaha you just did not understand me.
With out “ExecuteScalar()” your code always give True :slight_smile:

1 Like