MySQL与本地主机连接正常但不与IP地址连接

时间:2018-11-23 06:33:34

标签: java mysql localhost ip-address

我有一个Java程序,它从MySQL获取其信息,当我使用localhost连接到它时,它工作正常,但是每当我将ipaddress放入其中时,它都将不起作用。 我的连接代码和异常如下。

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"

6 个答案:

答案 0 :(得分:1)

该错误告诉您,ip Adress没有访问此数据库的权限,我认为这不是您的代码错误。

我不知道MySQL是否相同,但对于postgresql我 需要在数据库中定义以允许远程连接。

答案 1 :(得分:1)

我认为inetAddress.getHostAdress()将返回主机名(如Rp-Salh) 所以我建议您使用这种方法

inetAddress.getLocalHost()

答案 2 :(得分:0)

从错误日志中可以看到。 InetAddress.getLocalHost();未返回正确的IP地址。

请尝试通过提供硬编码的IP地址来进行连接(仅用于测试即可确定)。

您可以通过在CMD上键入ipconfig在Windows中获取系统IP地址。

答案 3 :(得分:0)

您需要确保两件事。

  1. 检查MySQl端口3306是否已打开。这是示例远程连接字符串

    字符串url =“ jdbc:mysql://192.168.1.121:3306 / ChatMaster”;

  2. 检查数据库用户名和密码是否正确。

答案 4 :(得分:0)

更新mysql配置文件(可能在服务器文件目录etc / mysql / my.conf中),检查是否已将127.0.0.1(默认)作为主机地址进行配置并将其更改为IP。

答案 5 :(得分:0)

事实证明,@ Jan。 St向我指出了正确的方向,因为问题不在我的代码中,也不是在获取ipaddress问题,这只是默认情况下在mysql中禁用了远程root访问。我只是按照以下链接中的答案进行了操作。

How to allow remote connection to mysql

注意:如果单独的第一个答案不起作用,请确保您也遵循同一帖子中的第二个答案。

相关问题