简体   繁体   中英

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

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

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.

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?

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.

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.

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..

update your drive version to:

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

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.

Hope this information helps...

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

So instead of using connection string as:

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

use

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

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:

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

  • check Operating System proxy settings

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

  • 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:

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

Usually default port for MySQL is 3306.

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

  • update your JDK driver library file
  • test different JDK and JREs (like JDK 6 and 7)
  • don't change max_allowed_packet

"[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.

  • change tomcat security

change TOMCAT6_SECURITY=yes to TOMCAT6_SECURITY=no

  • use validationQuery property

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

  • AutoReconnect

Add this code to your connection string:

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

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

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

  1. Check the amazon instance
  2. Check the security group of instance
  3. Assign the mysql/aura service and add your machine ip here or service provider ip .

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

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

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

#bind-address     = 127.0.0.1

Next, you will need to restart the database server:

sudo /etc/init.d/mysql restart

I had faced this issue and struggled a lot like a lot. I did everything single thing said in all the portals and not worked for me. The only thing which worked to me was updating my jar file to the current new version . Earlier I was using 5.1.38 and now updated to 8.0.15 and just that my program worked super fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM