I have a java program that connects to a MySql database and it's working fine. Now I want to convert it to a C# program, but I keep getting the error "Unable to connect to any of the specified hosts".
I've already followed the following solutions:
- Connect to MySql with C#
- C# MySqlConnector
- Configure the ODBC DNS
- And the reference to MySql.Data has been added to the project.
Here is the code to connect to the database:
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));
}
The java version connects to the same server with the same values as I used here, so please don't suggest checking if the server is online.
So the problem must be in my C# code, I noticed Class.forName("com.mysql.jdbc.Driver").newInstance ();
In the java code. Seems like the driver is made active here, maybe C# needs to do something similar that I'm missing?
Edit: So the connection string should be: string connectionString = string.Format("SERVER={0}; DATABASE={1}; Port={2}; UID={3}; PASSWORD={4};", host, dbName, port, userName, password));
Was using some extra elements from the java version, din't think they would cause these problems. Thanks for the help guys.