Home > Back-end >  How is correct to write connection string in c# web API on .NET Core?
How is correct to write connection string in c# web API on .NET Core?

Time:02-13

I write my connection string like that:

{
  "ConnectionStrings": {
    "AppCon": "Data Source=192.168.1.24:3306; Initial Catalog=dbName; User Id=UName; Password=Pass"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"

When I want to navigate in the url address I receive error:

SocketException: No such host is known.

and the debugger stuck at this method:

[HttpGet]
public JsonResult Get()
{
    string query = @"SELECT Station, Ime FROM auto_q_stations;";

    DataTable table = new DataTable();

    string sqlDataSource = _configuration.GetConnectionString("AppCon");

    MySqlDataReader myReader;

    using(MySqlConnection mycon = new MySqlConnection(sqlDataSource))
    {
        mycon.Open();
        using(MySqlCommand myCommand = new MySqlCommand(query, mycon))
        {
            myReader = myCommand.ExecuteReader();
            table.Load(myReader);

            myReader.Close();
            mycon.Close();
        }
    }
    return new JsonResult(table);
}

at this line:

mycon.Open();

What do I need to do to properly load my database?

CodePudding user response:

Remove the :3306 from the connection string; 3306 is the default so you don't need to specify it. If you do want to specify a non standard port, put eg Data Source=192.168.1.24;Port=12345;Initial Catalog=..

You can see the full list of keywords you can use in a connection string at: https://dev.mysql.com/doc/dev/connector-net/6.10/html/P_MySql_Data_MySqlClient_MySqlConnection_ConnectionString.htm

  • Related