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

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


当前回答

进入控制面板的“Windows服务”,启动MySQL服务。对我来说,这很有效。当我在做一个Java EE项目时,我得到了这个错误“通信链路故障”。我重启了我的系统,然后它就工作了。

之后,我再次得到相同的错误,即使重新启动我的系统。然后我尝试打开MySQL命令行控制台并以root登录,即使这样它也给了我一个错误。

最后,当我从Windows服务启动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.

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

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

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

在我的案例中,Soheil提供的解决方案是成功的。

澄清一下,我唯一需要做的改变是MySQL的服务器配置;

bind-address = **INSERT-IP-HERE**

我正在为我的应用程序使用一个外部MySQL服务器。它是一个基本的Debian 7.5安装MySQL服务器5.5 -默认配置。

重要的是:

始终备份您可能修改的任何配置文件的原始文件。当被提升为超级用户时一定要小心。

File

/etc/mysql/my.cnf

Line

bind-address        = 192.168.0.103 #127.0.0.1

重新启动MySQL服务器:

/usr/sbin/service mysql restart

如您所见,我只是提供了服务器的网络IP,并注释掉了默认条目。请注意,简单地复制和粘贴我的解决方案不会为您工作,除非奇迹我们的主机共享相同的IP。

谢谢@ Soheil

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

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

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