我试图连接到本地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

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


当前回答

在我的例子中,这是一个空闲超时,导致连接在服务器上断开。连接保持打开状态,但长时间没有使用。然后客户端重新启动工作,而我相信重新连接也会工作。

一个不错的解决方案是使用一个守护进程/服务来不时地ping连接。

其他回答

Windows系统:- 进入开始菜单,写“MySqlserver实例配置向导”,重新配置你的mysql服务器实例。 希望它能解决你的问题。

将bind-address设置为服务器的网络IP,而不是本地主机默认IP,并为我的用户设置特权,这对我来说很有效。

my.cnf:

bind-address = 192.168.123.456

MySql控制台:

GRANT ALL PRIVILEGES ON dbname.* to username@'%' IDENTIFIED BY 'password';

如果您正在使用hibernate,则此错误可能是由于保持打开Session对象的时间超过wait_timeout而导致的

我在这里记录了一个案例感兴趣的人可以看看。

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

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

因此,请检查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.