2014-10-20 128 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一样。