Java “com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链接失败”到远程数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21963923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:41:09  来源:igfitidea点击:

"com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure" to remote database

javamysqljdbcconnection

提问by chenupt

I tried to connect to my remote MySQL database, but I failed and got this error.

我试图连接到我的远程 MySQL 数据库,但我失败并收到此错误。

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The confusion is that It was effective when I used MySQL-Front tool to connect the remote database, and I can ping to the IP address successfully. but when I used my code, it wound show the error after about ten seconds.

令人困惑的是,当我使用MySQL-Front工具连接远程数据库时,它是有效的,并且可以成功ping通IP地址。但是当我使用我的代码时,它在大约十秒钟后显示错误。

Also when I used the wrong username or password in my code, it wound show the wrong verification immediately. Did that prove it is no problem to set up conection?

此外,当我在代码中使用错误的用户名或密码时,它会立即显示错误的验证。这是否证明建立连接没有问题?

Here is my code(It can work on my localhost database):

这是我的代码(它可以在我的本地主机数据库上运行):

public static void main(String[] args) {
        String url = "jdbc:mysql://(IP address):3306/";
        String dbName = "talk";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "talkroot";
        String password = "123456";
        try {
            Class.forName(driver).newInstance();
            Connection conn = DriverManager.getConnection(url + dbName,
                    userName, password);
            System.out.println("connect");
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("end");
    }

Here is the error:

这是错误:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Last packet sent to the server was 0 ms ago.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2120)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:723)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at com.test.TestMySQL.main(TestMySQL.java:16)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Last packet sent to the server was 21298 ms ago.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
    at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3009)
    at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2895)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3438)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1951)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2101)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2548)
    at com.mysql.jdbc.ConnectionImpl.configureClientCharacterSet(ConnectionImpl.java:1802)
    at com.mysql.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:3444)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2062)
    ... 12 more
Caused by: java.net.SocketException: Software caused connection abort: recv failed
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:113)
    at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:160)
    at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:188)
    at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2452)
    at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2906)
    ... 20 more

Anyone can help me please?

任何人都可以帮助我吗?

回答by Jingyuan Liu

you can try to replace the mysql-connector-java-version.jar jar file. Some people update the jar file from 5.1.10 to 5.1.14, then it works. Wish you are luck..

您可以尝试替换 mysql-connector-java-version.jar jar 文件。有些人将jar文件从5.1.10更新到5.1.14,然后就可以了。祝你好运。。

回答by Yogesh Funde

This com.mysql.jdbc.exceptions.jdbc4.CommunicationsException exception occurs if your database connection is idle for long time. This idle connection returns true on connection.isClosed(); but if we try to execute statement then it will fire this exception so I will suggest to go with database pooling.

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException 如果你的数据库连接长时间空闲就会出现这个异常。此空闲连接在 connection.isClosed() 上返回 true;但是如果我们尝试执行语句,那么它会触发这个异常,所以我建议使用数据库池。

回答by Search Results Web results Pi

Usually this error occurs when you don't use right port number. May be the machine which working on this database (client'db) has different port number. (Ex: 3307) .
Go task manager==> Services ==> services and check is there other version of mysql. if they use 3306 change your port to 3307.

通常当您不使用正确的端口号时会发生此错误。可能是在这个数据库(client'db)上工作的机器有不同的端口号。(例如:3307)。
转到任务管理器==> 服务==> 服务并检查是否有其他版本的mysql。如果他们使用 3306,请将您的端口更改为 3307。

回答by Aleja Chica

update your drive version to:

将您的驱动器版本更新为:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>

回答by Ram72119

Double Check the following things:

仔细检查以下事项:

  • Verify whether the IP address/Port Number is correct or not
  • Ping to the server using ping "IP address" it may tells is the server in startup mode/shutdown mode
  • If you are getting connection objects from connection pool, verify once connections availability.
  • 验证IP地址/端口号是否正确
  • 使用 ping “IP 地址” ping 到服务器它可能会告诉服务器处于启动模式/关闭模式
  • 如果您从连接池中获取连接对象,请验证一次连接可用性。

Hope this information helps...

希望这些信息有帮助...

回答by sahu

I solved it by removing the port number from the connection URL.

我通过从连接 URL 中删除端口号来解决它。

So instead of using connection string as:

因此,不要使用连接字符串作为:

jdbc:mysql://12x.xxx.xxx.xxx:1527/yourdbname

use

jdbc:mysql://12x.xxx.xxx.xxx/yourdbname

jdbc:mysql://12x.xxx.xxx.xxx/yourdbname

回答by hrk_er

Also when I used the wrong username or password in my code, it wound show the wrong verification immediately. Did that prove it is no problem to set up conection?

此外,当我在代码中使用错误的用户名或密码时,它会立即显示错误的验证。这是否证明建立连接没有问题?

this is probably done locally. so it doesn't relate to why your code isn't working.

这可能是在本地完成的。所以它与您的代码不起作用的原因无关。

There seems to be many ways to go about this, so you can try multiple things; people have solved this link failure in different ways as per their own situations:

似乎有很多方法可以解决这个问题,因此您可以尝试多种方法;人们根据自己的情况以不同的方式解决了这个链接失败:

Here are some the solutions:

以下是一些解决方案:

  • changing "bind-address" attribute
  • 更改“绑定地址”属性

Uncomment "bind-address" attribute or change it to one of the following IPs:

取消注释“绑定地址”属性或将其更改为以下 IP 之一:

bind-address="127.0.0.1"

绑定地址="127.0.0.1"

or

或者

bind-address="0.0.0.0"

绑定地址="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.

如果您的 MySQL 配置文件中有“skip-networking”行,请通过在该行的开头添加“#”符号来对其进行注释。

  • change "wait_timeout" and "interactive_timeout"
  • 更改“wait_timeout”和“interactive_timeout”

Add these lines to the MySQL config file:

将这些行添加到 MySQL 配置文件中:

[wait_timeout][1] = number

[wait_timeout][1] =数字

interactive_timeout = number

Interactive_timeout =数字

connect_timeout = number

连接超时 =数字

  • check Operating System proxy settings
  • 检查操作系统代理设置

Make sure the Fire wall, or Anti virus soft wares don't block MySQL service.

确保防火墙或防病毒软件不会阻止 MySQL 服务。

  • 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";

Make sure you don't have spaces in your string. All the connection string should be continues without any space characters.

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

Try to replace "localhost" with your port, like 127.0.0.1. Also try to add port number to your connection string, like:

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

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

Usually default port for MySQL is 3306.

通常 MySQL 的默认端口是 3306。

Don't forget to change username and password to the username and password of your MySQL server.

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

  • update your JDK driver library file
  • test different JDK and JREs (like JDK 6 and 7)
  • don't change max_allowed_packet
  • 更新您的 JDK 驱动程序库文件
  • 测试不同的 JDK 和 JRE(如 JDK 6 和 7)
  • 不要改变 max_allowed_pa​​cket

"[max_allowed_packet][4]" is a variable in MySQL config file that indicates the maximum packet size, not the maximum number of packets. So it will not help to solve this error.

“[max_allowed_pa​​cket][4]”是 MySQL 配置文件中的一个变量,表示最大数据包大小,而不是最大数据包数。所以它无助于解决这个错误。

  • change tomcat security
  • 更改 tomcat 安全性

change TOMCAT6_SECURITY=yes to TOMCAT6_SECURITY=no

将 TOMCAT6_SECURITY=yes 更改为 TOMCAT6_SECURITY=no

  • use validationQuery property
  • 使用validationQuery 属性

use validationQuery="select now()" to make sure each query has responses

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

  • AutoReconnect
  • 自动重连

Add this code to your connection string:

将此代码添加到您的连接字符串中:

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

回答by Mahadev

Your MySQL server isn't running. Check the same in the services page of the task manager if you are running Windows.

您的 MySQL 服务器没有运行。如果您运行的是 Windows,请在任务管理器的服务页面中检查相同内容。

回答by shivamindalkar

If you are working with Amazon Ubuntu instance then you have to follow this steps:

如果您正在使用 Amazon Ubuntu 实例,那么您必须按照以下步骤操作:

  1. Check the amazon instance
  2. Check the security group of instance
  3. Assign the mysql/auraservice and add your machine iphere or service provider ip.
  1. 检查亚马逊实例
  2. 查看实例的安全组
  3. 分配mysql/aura服务并在此处添加您的机器ip或服务提供商ip

回答by Noyal

Please update your mysql configuration file in /etc/mysql/my.cnf file

请在 /etc/mysql/my.cnf 文件中更新您的 mysql 配置文件

By default, MySQL only allows connections from the localhost address. The configuration file is usually found in /etc/mysql/my.cnf

默认情况下,MySQL 只允许来自 localhost 地址的连接。配置文件通常在/etc/mysql/my.cnf

You will want to comment out the bind-address line by making it look like this:

您需要通过使其看起来像这样来注释掉 bind-address 行:

#bind-address     = 127.0.0.1

Next, you will need to restart the database server:

接下来,您需要重新启动数据库服务器:

sudo /etc/init.d/mysql restart