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.Connectio开发者_StackOverflow社区nString = "Server=(servername);Username=(username);Pwd=(rightpassword);
Database=(rightdatabase)";
try
{
mysqlCon.Open();
}
catch (Exception ex)
{
MessageBox.Show("Could not establish a connection to database!");
}
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
.
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;
}
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
精彩评论