2014-10-20 129 views
-1

我只是試圖讀取控制檯上batabase中的內容,但我總是在conn.Open()行上得到一個異常。以下是所有代碼:使用C連接到000webhost上的mysql#

 SqlConnectionStringBuilder conn_string = new SqlConnectionStringBuilder(); 

     conn_string.DataSource = "mysql14.000webhost.com"; // Server 
     conn_string.UserID = "a7709578_codecal"; 
     conn_string.Password = "xxxxx"; 
     conn_string.InitialCatalog = "a7709578_codecal"; // Database name 

     SqlConnection conn = new SqlConnection(conn_string.ToString()); 

     conn.Open(); 
     SqlCommand cmd = new SqlCommand("Select name FROM Users"); 
     SqlDataReader reader = cmd.ExecuteReader(); 

     while (reader.Read()) 
     { 
      Console.WriteLine("{1}, {0}", reader.GetString(0), reader.GetString(1)); 
     } 

     reader.Close(); 
     conn.Close(); 

     if (Debugger.IsAttached) 
     { 
      Console.ReadLine(); 
     } 
+1

什麼是例外?發佈,以及。 – Rahul 2014-10-20 17:06:08

+0

'Sql *'類適用於Microsoft SQL Server。你對MySQL有什麼樣的驅動程序 - 一個ADO.NET的驅動程序?那將會有它自己的類。 ODBC?然後你應該使用OdbcConnection。 – Rup 2014-10-20 17:07:18

+0

你沒有使用正確的驅動程序cheeck它在這裏.. http://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-connection.html – NMK 2014-10-20 17:10:38

回答

1

您需要手動建立連接字符串或使用MySqlConnectionStringBuilder。 MySql使用與SQL Server不同的格式,並使用您正在使用的SqlConnectionStringBuilder。您還需要使用MySQL庫,SqlConnection,SqlCommand等都是專門爲SQL Server構建的。

MySQL connectors

1

MySQL數據庫使用的是錯誤的提供商。您在發佈的代碼中使用的這些類是SQL Server。你的代碼看起來應該像下面MySQL提供商相關的類

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder(); 
conn_string.Server = "mysql14.000webhost.com"; 
conn_string.UserID = "a7709578_codecal"; 
conn_string.Password = "xxxxxxx"; 
conn_string.Database = "a7709578_codecal"; 

using (MySqlConnection conn = new MySqlConnection(conn_string.ToString())) 

檢查Related post in SO

還指出可以看出

new SqlCommand("Select name FROM Users"); 

然而,你選擇從表中只有一列試圖檢索兩列值,這是不正確的

Console.WriteLine("{1}, {0}", reader.GetString(0), reader.GetString(1)) 
0

000webhost免費服務器不允許外部連接到服務器數據庫。

您只能使用存儲在服務器上的PHP腳本中的數據庫。

你可以使用PHP從數據庫中獲取數據,它會返回。所以我建議你使用C#的PHP像API一樣。