简体   繁体   中英

Connecting to mysql on 000webhost using C#

Im simply just trying to read what there is in the batabase on to a console but i always get an exception on the conn.Open() line. Here is all the code:

        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();
        }

You need to build the connection string manually or use MySqlConnectionStringBuilder . MySql uses a different format than SQL Server and the SqlConnectionStringBuilder that you're using. You also need to use a MySQL library, SqlConnection , SqlCommand , etc are all build specifically for SQL Server.

MySQL connectors

For MySQL database you are using wrong provider. Those classes you have used in posted code are for SQL Server . Your code should look like below with MySQL provider related classes

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()))

Check Related post in SO

Also to point out, you are selecting only one column from your table as can be seen

new SqlCommand("Select name FROM Users");

Whereas trying to retrieve two column value, which is not correct

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

000webhost free servers does not allow external connections to the server database.

You can only use your database from your PHP scripts stored on the server.

You can get data from database using PHP and it will return.So i advice to you using php from C# like api.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM