mysql与本地主机连接正常,但与ip地址不连接

9jyewag0  于 2021-06-17  发布在  Mysql
关注(0)|答案(6)|浏览(282)

我有一个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"
ozxc1zmp

ozxc1zmp1#

事实证明@jan.st为我指明了正确的方向,因为问题不在我的代码中,也不存在任何获取ipaddress的问题,只是默认情况下mysql中禁用了远程根访问。我只是在下面的链接中找到了答案,结果成功了。
如何允许远程连接mysql
注意:如果第一个答案本身不起作用,请确保您也遵循同一帖子中的第二个答案。

2ekbmq32

2ekbmq322#

我想 inetAddress.getHostAdress() 将返回主机名(suh as rp salh),因此我建议您使用此方法

inetAddress.getLocalHost()
mm9b1k5b

mm9b1k5b3#

从错误日志中可以看出。这个 InetAddress.getLocalHost(); 没有返回正确的ip地址。
请尝试通过提供硬编码的ip地址来连接它(只是为了测试以确定)。
您可以通过键入 ipconfig 按命令。

jum4pzuy

jum4pzuy4#

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

l5tcr1uw

l5tcr1uw5#

你需要确定两件事。
检查mysql端口 3306 是否已打开。下面是示例远程连接字符串
字符串url=“jdbc:mysql://192.168.1.121:3306/chatmaster“;
检查数据库用户名和密码是否正确。

xmd2e60i

xmd2e60i6#

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

相关问题