我试图连接到本地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客户端和远程mysql服务器之间的连接很弱。

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

其他回答

我也遇到过同样的问题。 发生这种情况是因为MySQL守护进程绑定到机器的IP,这是与有权限连接@your_machine的用户建立连接所必需的。 在这种情况下,用户应该拥有连接USER_NAME@MACHINE_NAME_OR_IP的权限

我想要远程访问我的机器,所以我把my.cnf从

bind-address = MY_IP_ADDRESS

To

bind-address = 0.0.0.0

这将允许来自本地主机和甚至外部(在我的例子中)的用户连接到实例。 如果你将MySQL绑定为0.0.0.0,下面两个权限都可以工作:

USER_NAME@MACHINE_NAME_OR_IP

USER_NAME@localhost

对我来说,解决方案是在mysql服务器的conf文件中修改参数bind-address="127.0.0.1"或bind-address=" x.x.x.x "。to bind-address="0.0.0.0"。 谢谢。

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

我也遇到过类似的问题,我的解决方案是

改变bind-address = 0.0.0.0从127.0.0.1 更改url的localhost为localhost:3306

我觉得我们永远不应该放弃,我尝试了这篇文章和其他论坛上的所有选择…很高兴它能起作用@saurab

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

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.