skip to Main Content

I want to connect with a server’s MySql DB(cpanel) . Though there are no errors every time I’m getting a message for Messegebox : unable to connect to any of the specified any of the MySql hosts.

output type

using MySql.Data.MySqlClient;
        connString = "SERVER = ********;PORT=3306;DATABASE=********;UID=**********;PASSWORD=*********";
        try
        {
            conn = new MySqlConnection();
            conn.ConnectionString = connString;
            conn.Open();
            MessageBox.Show("Server is online");

        }
        catch (MySql.Data.MySqlClient.MySqlException ex)
        { MessageBox.Show(ex.Message);}

3

Answers


  1. I would look into using ConnectionStringBuilder. Also note the use of ‘using’. This will ensure resources are disposed once finished with.

    private MySqlConnectionStringBuilder sConnString = new MySqlConnectionStringBuilder
    {
        Server = "",
        UserID = "",
        Password = "",
        Database = ""
    };
    
    private void Test(){
    
        // open connection to db
        using (MySqlConnection conn = new MySqlConnection(sConnString.ToString()))
        {
            using (MySqlCommand cmd = conn.CreateCommand())
            {
                try
                {
                    conn.Open();
                    cmd.CommandText = "SELECT * FROM foo WHERE OrderID = @OrderID";
    
                    // Add any params
                    cmd.Parameters.AddWithValue("@OrderID", "1111");
                    cmd.Prepare();
                    cmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                    return;
                }
            }
        }
    }
    
    Login or Signup to reply.
  2. If you try to connect to your MySQL server externally, external connections need to be enabled.

    Be aware that it is a security hole if you provide your app to others which contain the DB information. To go around that, you need to create a Web-API.

    Login or Signup to reply.
  3. The first step to connect to your app to a remote server MySql Server is verify if it allows external connections, for default the root user is locked, to allow local you can try to connect with the root user typing the following command in MySql:

     GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
     FLUSH PRIVILEGES;
    'root': You can change it with your user.
    '%': allows all connections, you can limit it typing an IP.
    

    Second step is verify your MySql .net connector

    Cheers!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search