2010-08-26 145 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