Marcus
Marcus

Reputation: 449

Connecting with MySQL.NET connector

I'm getting error:

Could not establish a connection to database

when I connect with MySQL .NET connector. I'm fully sure of that the username is right, the password is right, the database is right, and the server is right. Here's the code:

mysqlCon.ConnectionString = "Server=(servername);Username=(username);Pwd=(rightpassword); 
Database=(rightdatabase)";
try
{
    mysqlCon.Open();
}
catch (Exception ex)
{
    MessageBox.Show("Could not establish a connection to database!");
}

Upvotes: 0

Views: 274

Answers (3)

abatishchev
abatishchev

Reputation: 100288

Make sure that the database is reachable from the machine you're running the code.

Use telnet

telnet <server> 3306

or MySQL command line client

mysql -u <user> -h <server> -P <port> -p

Upvotes: 0

Marco
Marco

Reputation: 57583

I use:

public MySqlConnection NewConnection(string host, int port, string db, string user, string pwd)
{
    string cstr = String.Format(
        "SERVER={0};PORT={1};DATABASE={2};UID={3};PWD={4}",
        host, port, db, user, pwdd);
    MySqlConnection conn = new MySqlConnection(cstr);
    try { conn.Open(); }
    catch (Exception ex)
    {
        conn = null;
    }
    return conn;
}

Upvotes: 1

Damb
Damb

Reputation: 14600

Shouldn't you use Uid instead of Username? At least connectionstrings.com says so :)
And also check what port is your MySQL running at. You might need to add port number to your connection string if you aren't using the default one - 3306.

Upvotes: 1

Related Questions