我有一个Java程序连接到MySql数据库,它工作正常。 现在我想将它转换为C#程序,但我一直收到错误“无法连接到任何指定的主机”。C#MySql连接无法找到主机
我已经遵循了以下解决方案:
- Connect to MySql with C#
- C# MySqlConnector
- Configure the ODBC DNS
- 并以MySql.Data参考已经被添加到项目中。
这里是连接到数据库的代码:
string connectionString = string.Format(
"SERVER={0}; DATABASE={1}; UID={2}; PASSWORD={3};",
"jdbc:mysql://" + host + ":" + port, dbName, userName, password);
// Prepare connecting to the database.
myConn = new MySqlConnection(connectionString);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = @"SELECT * FROM table_name";
myConn.Open(); // <- MySqlException: Unable to connect to any of the specified MySQL hosts.
MySqlDataReader reader = command.ExecuteReader();
List<string> exampleStore = new List<string>();
while (reader.Read())
{
// Just an example for storing data.
exampleStore.Add(reader.GetString(0));
}
Java版本连接到同一台服务器使用相同的价值观我这里使用的,所以请不要建议如果检查服务器在线。 所以这个问题一定是在我的C#代码中,我注意到了Class.forName("com.mysql.jdbc.Driver").newInstance();
在java代码中。似乎这里的驱动程序是活跃的,也许C#需要做类似的东西,我错过了?所以连接字符串应该是:string connectionString = string.Format(“SERVER = {0}; DATABASE = {1}; Port = {2}; UID = {3}; PASSWORD = {4}}; ;“,host,dbName,port,userName,password));
正在使用java版本中的一些额外元素,但不认为它们会导致这些问题。谢谢你们的帮助。
您试图更改连接字符串?试试这个:'“Data Source =”+ Server_IP +“;” +“用户ID =”+用户名+“;” +“Password =”+ Password +“;”' – Cipi 2010-08-26 10:34:31
感谢您的建议,尝试过但同样的错误,虽然在显示错误之前需要很长的时间。还试过指定>“数据库=”+ dbName <但也不能工作。 – MrFox 2010-08-26 10:49:20