2010-08-26 140 views
0

我有一个Java程序连接到MySql数据库,它工作正常。 现在我想将它转换为C#程序,但我一直收到错误“无法连接到任何指定的主机”。C#MySql连接无法找到主机

我已经遵循了以下解决方案:

  1. Connect to MySql with C#
  2. C# MySqlConnector
  3. Configure the ODBC DNS
  4. 并以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版本中的一些额外元素,但不认为它们会导致这些问题。谢谢你们的帮助。

+0

您试图更改连接字符串?试试这个:'“Data Source =”+ Server_IP +“;” +“用户ID =”+用户名+“;” +“Password =”+ Password +“;”' – Cipi 2010-08-26 10:34:31

+0

感谢您的建议,尝试过但同样的错误,虽然在显示错误之前需要很长的时间。还试过指定>“数据库=”+ dbName <但也不能工作。 – MrFox 2010-08-26 10:49:20

回答

1

标准连接字符串是: Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;

请注意,端口单独指定,端口= 1234,不在服务器字段中。另外,从服务器字段的开始处消除jdbc:mysql:,因为它特定于JDBC驱动程序;使用普通的URI字符串。没有别的东西需要。

+0

感谢您的解释 – MrFox 2010-08-26 11:12:46

1

您的连接字符串错误。

尝试:

string connectionString = string.Format("SERVER={0}; DATABASE={1}; Port={2}; UID={3}; PASSWORD={4};", host, dbName, port, userName, password)); 
+0

感谢这工作:),我标记亚历克斯作为答案,因为他是第一个,并解释它。 – MrFox 2010-08-26 11:12:31