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

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


当前回答

如果你使用的是MAMP PRO,那么很容易就能解决这个问题,我真希望在我开始在互联网上搜索几天试图解决这个问题之前就已经意识到这一点。真的很简单…

你只需要从MAMP MySQL选项卡中点击“允许网络访问MySQL”。

真的,就是这样。

哦,你可能仍然需要将绑定地址更改为0.0.0.0或127.0.0.1,就像上面文章中概述的那样,但是如果你是一个MAMP用户,只单击这个框就可能解决你的问题。

其他回答

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

在我的例子中,当MySQL没有足够的内存时就会发生这种情况。重新启动可以修复它,但如果是这种情况,请考虑使用内存更大的机器,或者限制jvm占用的内存

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

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

多年来一直有同样的问题,没有永久的解决方案,这是过去3周解决的问题(这是一个无错误操作的记录)

设置全局wait_timeout=3600; 设置全局交互超时=230400;

如果这对你有用,别忘了把它变成永久性的。

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

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.