连接被拒绝:连接,无法连接数据库mysql

时间:2017-05-12 19:42:28

标签: java mysql

我无法连接远程数据库。当我在localhost上连接我自己的数据库时,它会连接。怎么了?

    Exception in thread "main" java.lang.IllegalStateException: Cannot connect the database!

    Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

Caused by: java.net.ConnectException: Connection refused: connect

Java代码:

String url = "jdbc:mysql://ipadress:3306/database?autoReconnect=true&useSSL=false";
        String username = "username";
        String password = "password";
        String query = "SELECT * FROM database";

        System.out.println("Connecting database...");
          try {
        // The newInstance() call is a work around for some
        // broken Java implementations

        Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (Exception ex) {
        // handle the error
    }
        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            System.out.println("Database connected!");
            //Uruchamiamy zapytanie do bazy danych
                        Statement stmt = connection.createStatement();
                        ResultSet rs = stmt.executeQuery(query);

                        while (rs.next()) {

                        }

                        connection.close();
        } catch (SQLException e) {
        throw new IllegalStateException("Cannot connect the database!", e);
        }
    }

我可以在PHPMyAdmin上登录数据库,我没有root帐户,它是我朋友的数据库。我检查端口3306是否在此处打开:http://www.yougetsignal.com/tools/open-ports/并且它已关闭。我在哪里可以打开它?在路由器设置中"端口转发"?我应该设置哪些私有IP和类型(TCP或UDP)来打开此端口?

1 个答案:

答案 0 :(得分:0)

(道歉,如果这个答案不完整,但有太多不适合评论)

1)不要忽视异常。这很糟糕:使用// handle the error并且catch块中没有其他内容,如果出现错误,您的代码将不报告错误,并且将继续执行(它应该退出/中断/返回,具体取决于代码的位置)。

2)我认为检查"SHOW GLOBAL VARIABLES LIKE 'PORT';"是不够的。询问您的朋友数据库守护程序是否实际侦听到您可以访问的网络接口上的端口3306。 MySQL可配置为禁用网络(skip-networking),或已启用,但仅适用于本地计算机(bind-address=127.0.0.1localhost - 它应为bind-address=0.0.0.0bind-address=hostname或公共IP地址......)。

要自己检查一下,如果您使用的是Linux,请尝试使用nctelnet(如果您没有,请安装nc):{{1} }。如果你得到"连接被拒绝",那么错误肯定不在你的java代码中,而是在服务器设置中。