简体   繁体   中英

How to connect ASP.NET Web Api project with hosted mySQL database?

I am working with an api web application that is connected to mysql database using Visual Studio for Mac, my problem is that when I try to connect with hosted mysql db in the server I got the following exception "Unable to connect to any of the specified MySQL hosts." However, when you connect to the local db mysql by using XAMPP, the connection works well and successfully.

here is my code.

in Program.cs

  public static MySqlConnection Conn(){

         var connection_string = "Data Source=MYSQL5015.site4now.net;Initial Catalog=db_a42078_holzqp;User ID=xxxxxx;Password=xxxxxxx";

        var conn = new MySqlConnection(connection_string);

        return conn;
    }

in ValuesController.cs

public string Get(int id){ 
        conn = Program.Conn();
        try
        {
            conn.Open();
        }
        catch (MySqlException ex)
        {
            return "Failure: " + ex.Message.ToString();
        }
        if(conn.State == System.Data.ConnectionState.Open){
            return "opened";
        }else{
            return "closed";
        }}

Note : i also tried the standard mysql connection string like "SERVER:XXX;DATABASE=XXX;UID=XXXX;PWD=XXXX" and i got the same exception.

please help and thanks for all

My first guess, is that the error you are getting indicates it couldn't find the host name (a DNS issue). So, if the issue is around the server name in your connection string you can try 1 of 2 things:

  1. Point to a localhost or server, something you know is resolvable from your computer.
  2. Use an IP address instead of server name

You can use your " Network Utility ", since you are using MAC, to discard if this is a DNS issue by ping ing the server name and it will probably give you the same error if it can't resolve the name. This will also give you the IP Address if you want to use this to connect.

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