我试图连接到本地MySQL服务器,但我一直得到一个错误。

这是代码。

public class Connect {

    public static void main(String[] args) {
        Connection conn = null;

        try {
            String userName = "myUsername";
            String password = "myPassword";

            String url = "jdbc:mysql://localhost:3306/myDatabaseName";
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(url, userName, password);
            System.out.println("Database connection established");
        } catch (Exception e) {
            System.err.println("Cannot connect to database server");
            System.err.println(e.getMessage());
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                    System.out.println("Database Connection Terminated");
                } catch (Exception e) {}
            }
        }
    }
}

错误是:

Cannot connect to database server
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.
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.
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
        at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
        at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
        at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2333)
        at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2370)
        at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2154)
        at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:792)
        at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
        at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
        at java.sql.DriverManager.getConnection(DriverManager.java:582)
        at java.sql.DriverManager.getConnection(DriverManager.java:185)
        at Connect.main(Connect.java:16)
    Caused by: java.net.ConnectException: Connection refused
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
        at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
        at java.net.Socket.connect(Socket.java:529)
        at java.net.Socket.connect(Socket.java:478)
        at java.net.Socket.<init>(Socket.java:375)
        at java.net.Socket.<init>(Socket.java:218)
        at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:257)
        at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:294)
        ... 15 more

我已经设置了类路径,确保my.cnf有跳过网络选项注释掉。

Java版本为1.2.0_26(64位) mysql 5.5.14 Mysql连接器5.1.17

我确保用户可以访问我的数据库。


当前回答

我只是重新启动MySQL(从这里的提示:https://stackoverflow.com/a/14238800),它解决了这个问题。

我在通过homebrew安装的MacOS(10.10.2)和MySql(5.6.21)上也有同样的问题。

令人困惑的是,我的一个应用程序可以连接到数据库,而另一个则不能。

在应用程序上尝试了许多东西,抛出了com.mysql.jdbc.CommunicationsException异常,这是这个问题的公认答案所建议的,但没有效果,我很惊讶重新启动MySQL工作了。

我的问题的原因可能如下所示,在上述链接的回答:

您是否使用连接池?如果是,请尝试重新启动 服务器。连接池中可能只有少数连接处于关闭状态。

其他回答

如果你在一组Docker容器上遇到了问题,那么确保你不仅暴露了端口3306,而且还从容器-p 3306:3306外部映射了端口。docker-compose.yml:

version: '2'

services:
    mdb:
        image: mariadb:10.1
        ports:
            - "3306:3306"
        …

在我的情况下(我是一个新手),我正在测试Servlet,使数据库与MySQL连接,其中一个异常是上面提到的。

这让我的头摇摆了几秒钟,但我意识到这是因为我没有启动我的MySQL服务器在本地主机。 启动服务器后,问题得到了解决。

因此,请检查MySQL服务器是否正常运行。

就我而言,

修改远程机器mysql的配置:/etc/mysql/my.cnf: Change Bind-address = 127.0.0.1 来 #bind-address = 127.0.0.1 在远程机器上,将mysql用户权限更改为 授予*上的所有特权。*到'用户'@'%'由'密码'识别; 注意:在远程机器上重新启动mysql: sudo /etc/init.d / mysql重启

在我的两个程序中,我也遇到了同样的问题。我的错误是:

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.

我花了几天时间来解决这个问题。我已经测试了不同网站上提到的许多方法,但没有一种有效。最后,我修改了我的代码,发现了问题所在。我将试着告诉你们不同的方法,并在这里进行总结。

当我在互联网上寻找这个错误的解决方案时,我发现有许多解决方案至少对一个人有效,但其他人说它对他们不起作用!为什么有很多方法来解决这个错误? 当连接到服务器时出现问题时,通常会出现这种错误。问题可能是由于错误的查询字符串或到数据库的连接太多。

所以我建议你一个一个尝试所有的解决方案,不要放弃!

以下是我在网上找到的解决方案,对于每一个解决方案,至少有一个人的问题已经用这个解决方案解决了。

提示:对于需要更改MySQL设置的解决方案,您可以参考以下文件:

Linux: /etc/mysql/my.cnf或/etc/my.cnf(取决于所使用的Linux发行版和MySQL包) Windows: C:\**ProgramData**\MySQL\MySQL Server 5.6\my.ini(注意是ProgramData,不是Program Files)

以下是解决方案:

changing bind-address attribute: Uncomment bind-address attribute or change it to one of the following IPs: bind-address="127.0.0.1" or bind-address="0.0.0.0" commenting out "skip-networking" If there is a skip-networking line in your MySQL config file, make it comment by adding # sign at the beginning of that line. change "wait_timeout" and "interactive_timeout" Add these lines to the MySQL config file: [wait_timeout][1] = *number* interactive_timeout = *number* connect_timeout = *number* Make sure Java isn't translating 'localhost' to [:::1] instead of [127.0.0.1] Since MySQL recognizes 127.0.0.1 (IPv4) but not :::1 (IPv6) This could be avoided by using one of two approaches: In the connection string use 127.0.0.1 instead of localhost to avoid localhost being translated to :::1 Run java with the option -Djava.net.preferIPv4Stack=true to force java to use IPv4 instead of IPv6. On Linux, this could also be achieved by running (or placing it inside /etc/profile: export _JAVA_OPTIONS="-Djava.net.preferIPv4Stack=true" check Operating System proxy settings, firewalls and anti-virus programs Make sure the Firewall, or Anti-virus software isn't blocking MySQL service. Stop iptables temporarily on linux. If iptables are misconfigured they may allow tcp packets to be sent to mysql port, but block tcp packets from coming back on the same connection. # Redhat enterprise and CentOS systemctl stop iptables.service # Other linux distros service iptables stop Stop anti-virus software on Windows. change connection string Check your query string. your connection string should be some thing like this: dbName = "my_database"; dbUserName = "root"; dbPassword = ""; String connectionString = "jdbc:mysql://localhost/" + dbName + "?user=" + dbUserName + "&password=" + dbPassword + "&useUnicode=true&characterEncoding=UTF-8";

确保字符串中没有空格。所有的连接字符串应该是连续的,没有任何空格字符。

尝试将“localhost”替换为环回地址127.0.0.1。 还可以尝试将端口号添加到连接字符串中,例如:

String connectionString = "jdbc:mysql://localhost:3306/my_database?user=root&password=Pass&useUnicode=true&characterEncoding=UTF-8";

通常MySQL的默认端口是3306。

请不要忘记将用户名和密码修改为MySQL服务器的用户名和密码。

更新JDK驱动程序库文件 测试不同的JDK和JREs(如JDK 6和7) 不要改变max_allowed_packet

“max_allowed_packet”是MySQL配置文件中的一个变量,表示最大数据包大小,而不是最大数据包数。所以它对解决这个错误没有帮助。

更改tomcat安全性

将TOMCAT6_SECURITY=yes修改为TOMCAT6_SECURITY=no

使用validationQuery属性

使用validationQuery="select now()"确保每个查询都有响应

自动重新连接

将以下代码添加到连接字符串中:

&autoReconnect=true&failOverReadOnly=false&maxReconnects=10

虽然这些方法对我都不起作用,但我建议你试一试。因为有些人按照这些步骤解决了他们的问题。

但是什么解决了我的问题?

我的问题是我在数据库中有很多select。每次我都在建立联系,然后又关闭它。虽然我每次都在关闭连接,但系统面临许多连接,给了我这个错误。我所做的是将连接变量定义为整个类的公共(或私有)变量,并在构造函数中初始化它。每次我利用这种联系。它解决了我的问题,也大大提高了我的速度。

#Conclusion# There is no simple and unique way to solve this problem. I suggest you to think about your own situation and choose above solutions. If you take this error at the beginning of the program and you are not able to connect to the database at all, you might have problem in your connection string. But If you take this error after several successful interaction to the database, the problem might be with number of connections and you may think about changing "wait_timeout" and other MySQL settings or rewrite your code how that reduce number of connections.

这主要是因为mysql客户端和远程mysql服务器之间的连接很弱。

在我的情况下,这是因为不稳定的VPN连接。