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

标签 java mysql localhost ip-address

我有一个从 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/

相关文章:

java - 在 Spring Boot 应用程序的应用程序属性文件中使用 Jenkins 变量

java - Android 中的内置布局是否可样式化?

java - 检测在 View 上滑动

mysql - Oracle SQL 开发人员错误 : vendor code 1317

mysql - 如何在mysql中同时选择true和false列值

python - 在同一本地主机上的python本地主机请求具有不同的端口

java - 使用开放式套接字在 Tomcat 上进行并行部署?

php - 如何使用 PHP 为 MySQL 表中的每一行重新分配 AUTO_INCREMENT 列

javascript - 在 tomcat 服务器(本地主机)上运行时未显示 amcharts

python - 从其他计算机访问 Django 应用程序