我有一個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