Reputation: 5126
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:
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.
Upvotes: 0
Views: 4076
Reputation: 9209
Your connection string is wrong.
Try:
string connectionString = string.Format("SERVER={0}; DATABASE={1}; Port={2}; UID={3}; PASSWORD={4};", host, dbName, port, userName, password));
Upvotes: 1
Reputation: 5549
The standard connection string is:
Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
.
Please note that the port is specified separately, with Port=1234, not in the Server field. Also, eliminate jdbc:mysql:
from the start of the server field, as it's specific to the JDBC driver; use a normal URI string. Nothing else should be needed.
Upvotes: 1