Check Database Connection in MySQL using C#

Step 1: Add Reference of MySql.Data.dll

Step 2: Add a class file with named MYSQL.CS

Step 3: Add the following name space

using MySql.Data.MySqlClient;
using MySql.Data;

Step 4: Write the below code in cs file to check the connection is working or not.

public bool check_connection(string conn)

{

    bool result = false;

    MySqlConnection connection = new MySqlConnection(conn);

    try

    {

        connection.Open();

        result = true;

        connection.Close();

    }

    catch

    {

        result = false;

    }

    return result;

}


Step 5: To use above function please write the below code.

Create instance of class:

MYSQL mysql = new MYSQL();

Use it in Button event or anywhere.
         

source_result = mysql.check_connection("Your connection String");

if (source_result == false)

{

    lbl_error.Text = lbl_error.Text + " ::Error In Source Connection";

}