gpt4 book ai didi

java - Mysql与本地主机连接正常但无法连接IP地址

转载 作者:行者123 更新时间:2023-11-29 01:15:35 25 4
gpt4 key购买 nike

我有一个从 MySQL 获取信息的 java 程序,当我使用 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"

最佳答案

正如错误告诉您的那样,ip 地址没有访问此数据库的权限,我认为这不是您的代码错误。

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

关于java - Mysql与本地主机连接正常但无法连接IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53441646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com