I’m trying to create an API server, and I need to have access to MySQL database. I have this piece of code:
public static class Database
{
private const string ConnectionString = "Server=localhost;Port=3306;Database=contoso_inc;Uid=root;Pwd=f6e527xp;";
public static IEnumerable<User> Execute(string query)
{
using (var connection = new SqlConnection(ConnectionString))
{
var command = new SqlCommand(query, connection);
connection.Open();
var reader = command.ExecuteReader();
var result = new List<User>();
while (reader.Read())
{
var user = new User
{
year = (uint) reader.GetValue(0),
month = (string) reader.GetValue(1),
users_num = (uint) reader.GetValue(2)
};
result.Add(user);
}
reader.Close();
return result;
}
}
}
The error appears on this line: connection.Open();
. So apparently I can’t use Port for some reason. What is the problem?
P.S. I’ve seen related questions, but most of them belong to the Entity Framework topic. I don’t have DbContext
here, so it didn’t help.
3
Answers
The port is specified in the Server keyword, in your example use:
connection string is documented here: https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.connectionstring?view=dotnet-plat-ext-5.0
Looking at the documentation for
SqlConnection.ConnectionString
, I don’t see any sign of a key for "port". If you need to specify the port, you can do so in theServer
part:So perhaps you want: "Server=localhost,3306;…" or "Server=tcp:localhost,3306;…" – if you actually think you need to really need to specify the port at all.
I think you’re using the wrong driver for connect.
try install this nuget package
then, you can do something like this: