我有一个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"发布于 2018-11-23 08:36:20
事实证明,@ just为我指出了正确的方向,因为问题不在我的代码中,也不是在获取I地址问题上,这只是因为默认情况下,mysql中禁用了远程根访问。我只是在下面的链接中跟踪了答案,结果成功了。
How to allow remote connection to mysql
注意:如果第一个答案本身不起作用,请确保你在同一篇文章中跟随第二个答案。
发布于 2018-11-23 06:39:04
正如错误告诉您的,ip Adress没有访问此数据库的权限,我认为错误的不是您的代码。
我不知道MySQL是否相同,但对于postgresql,我需要在数据库中定义以允许远程连接。
发布于 2018-11-23 06:39:56
我认为inetAddress.getHostAdress()将返回主机名(suh为Rp-Salh),因此我建议您使用此方法。
inetAddress.getLocalHost()https://stackoverflow.com/questions/53441646
复制相似问题