我有一个java程序,它从MySQL获取信息,当我使用本地主机连接到它时,它工作得很好,但当我在其中放入IP地址时,它就不工作了。
我的连接代码和异常如下。

package connection;

import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;

/**
 *
 * @author rpsal
 */
public class DBConnection {

    public static Connection connect()//working  on local host
    {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://"+getIpAddress()+"/ChatMaster";
            conn = DriverManager.getConnection(url, "root", "");
        } catch (Exception e) {
            System.out.println("Exception in connect" + e);
        }
        return conn;
    }

    public static String getIpAddress() throws Exception {
        InetAddress inetAddress = InetAddress.getLocalHost();
        return inetAddress.getHostAddress();
    }
}

当我使用String url = "jdbc:mysql:///ChatMaster";时,它工作正常。
我得到的例外情况如下。
Exception in connectjava.sql.SQLException: null,  message from server: "Host 'Rp-Salh' is not allowed to connect to this MySQL server"

最佳答案

正如错误告诉你的,ip地址没有访问这个数据库的权限,我认为错误的不是你的代码。
我不知道MySQL是否也一样,但postgresql I
需要在数据库中定义以允许远程连接。

10-07 19:28
查看更多