java – Solving a “communications link failure” with JDBC and MySQL

The Question :

213 people think this question is useful

I’m trying to connect to the local MySQL server but I keep getting an error.

Here is the code.

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";
            conn = DriverManager.getConnection(url, userName, password);
            System.out.println("Database connection established");
        } catch (Exception e) {
            System.err.println("Cannot connect to database server");
        } finally {
            if (conn != null) {
                try {
                    System.out.println("Database Connection Terminated");
                } catch (Exception e) {}

and the errors :

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(
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(
        at java.lang.reflect.Constructor.newInstance(
        at com.mysql.jdbc.Util.handleNewInstance(
        at com.mysql.jdbc.SQLError.createCommunicationsException(
        at com.mysql.jdbc.MysqlIO.<init>(
        at com.mysql.jdbc.ConnectionImpl.coreConnect(
        at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(
        at com.mysql.jdbc.ConnectionImpl.createNewIO(
        at com.mysql.jdbc.ConnectionImpl.<init>(
        at com.mysql.jdbc.JDBC4Connection.<init>(
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(
        at java.lang.reflect.Constructor.newInstance(
        at com.mysql.jdbc.Util.handleNewInstance(
        at com.mysql.jdbc.ConnectionImpl.getInstance(
        at com.mysql.jdbc.NonRegisteringDriver.connect(
        at java.sql.DriverManager.getConnection(
        at java.sql.DriverManager.getConnection(
        at Connect.main(
    Caused by: Connection refused
        at Method)
        at com.mysql.jdbc.StandardSocketFactory.connect(
        at com.mysql.jdbc.MysqlIO.<init>(
        ... 15 more

I’ve set the classpath, made sure my.cnf had the skip network option commented out.

java version is 1.2.0_26 (64 bit) mysql 5.5.14 mysql connector 5.1.17

I made sure that the user had access to my database.

The Question Comments :
  • Note the CausedBy at the bottom. The SQL server never accepted the connection. What happens if do (from a command line) telnet localhost 3306? Is the mySQL server running?
  • Check this post. Might help:…
  • Problem solved, added a bind-address entry to my.cnf.
  • @Anthony You should put your comment as an answer and accept it …
  • I tried going to Windows Services in Control Panel and started mysql service and then it worked..try this solution

The Answer 1

405 people think this answer is useful

I have had the same problem in two of my programs. My error was this:

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.

I spent several days to solve this problem. I have tested many approaches that have been mentioned in different web sites, but non of them worked. Finally I changed my code and found out what was the problem. I’ll try to tell you about different approaches and sum them up here.

While I was seeking the internet to find the solution for this error, I figured out that there are many solutions that worked for at least one person, but others say that it doesn’t work for them! why there are many approaches to this error? It seems this error can occur generally when there is a problem in connecting to the server. Maybe the problem is because of the wrong query string or too many connections to the database.

So I suggest you to try all the solutions one by one and don’t give up!

Here are the solutions that I found on the internet and for each of them, there is at least on person who his problem has been solved with that solution.

Tip: For the solutions that you need to change the MySQL settings, you can refer to the following files:

  • Linux: /etc/mysql/my.cnf or /etc/my.cnf (depending on the Linux distribution and MySQL package used)

  • Windows: C:**ProgramData**\MySQL\MySQL Server 5.6\my.ini (Notice it’s ProgramData, not Program Files)

Here are the solutions:

  • changing “bind-address” attribute

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




  • 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 = number

interactive_timeout = number

connect_timeout = number

  • Make sure Java isn’t translating ‘localhost’ to [:::1] instead of []

Since MySQL recognizes (IPv4) but not :::1 (IPv6)

This could be avoided by using one of two approaches:

Option #1: In the connection string use instead of localhost to avoid localhost being translated to :::1

Option #2: Run java with the option 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=""

  • 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 + "&amp;password=" + dbPassword + "&amp;useUnicode=true&amp;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 the loopback address Also try to add port number to your connection string, like:

String connectionString = "jdbc:mysql://localhost:3306/my_database?user=root&amp;password=Pass&amp;useUnicode=true&amp;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” 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


  • use validationQuery property

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

  • AutoReconnect

Add this code to your connection string:


Although non of these solutions worked for me, I suggest you to try them. Because there are some people who solved their problem with following these steps.

But what solved my problem?

My problem was that I had many SELECTs on database. Each time I was creating a connection and then closing it. Although I was closing the connection every time, but the system faced with many connections and gave me that error. What I did was that I defined my connection variable as a public (or private) variable for whole class and initialized it in the constructor. Then every time I just used that connection. It solved my problem and also increased my speed dramatically.


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.

The Answer 2

14 people think this answer is useful

If you are using MAMP PRO, the easy fix, which I really wish I had realized before I started searching the internet for days trying to figure this out. Its really this simple…

You just have to click “Allow Network Access to MySQL” from the MAMP MySQL tab.

Really, thats it.

Oh, and you MIGHT have to still change your bind address to either or like outlined in the posts above, but clicking that box alone will probably solve your problems if you are a MAMP user.

The Answer 3

5 people think this answer is useful

Setting the bind-address to the server’s network IP instead of the localhost default, and setting privileges on my user worked for me.


bind-address =

MySql Console:

GRANT ALL PRIVILEGES ON dbname.* to username@'%' IDENTIFIED BY 'password';

The Answer 4

4 people think this answer is useful

In my case,

  1. Change the remote machine mysql configuration at /etc/mysql/my.cnf: change bind-address = to #bind-address =

  2. On the remote machine, change mysql user permissions with GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' IDENTIFIED BY 'password';

  3. IMPORTANT: restart mysql on the remote machine: sudo /etc/init.d/mysql restart

The Answer 5

4 people think this answer is useful

I’ve just faced the same problem. It happened because the MySQL Daemon was binded to the IP of the machine, which is required to make connection with an user that has permission to connect @your_machine. In this case, the user should have permission to connect USER_NAME@MACHINE_NAME_OR_IP

I wanted remote access to my machine so I changed in my.cnf from

bind-address = MY_IP_ADDRESS


bind-address =

Which will allow an user from localhost AND even outside (in my case) to connect to the instance. Both below permissions will work if you bind the MySQL to



The Answer 6

4 people think this answer is useful

In my case (I am a noob), I was testing Servlet that make database connection with MySQL and one of the Exception is the one mentioned above.

It made my head swing for some seconds but I came to realize that it was because I have not started my MySQL server in localhost.
After starting the server, the problem was fixed.

So, check whether MySQL server is running properly.

The Answer 7

3 people think this answer is useful

In my case it was an idle timeout, that caused the connection to be dropped on the server. The connection was kept open, but not used for a long period of time. Then a client restart works, while I believe a reconnect will work as well.

A not bad solution is to have a daemon/service to ping the connection from time to time.

The Answer 8

3 people think this answer is useful

As the detailed answer above says, this error can be caused by many things.

I had this problem too. My setup was Mac OSX 10.8, using a Vagrant managed VirtualBox VM of Ubuntu 12.04, with MySQL 5.5.34.

I had correctly setup port forwarding in the Vagrant config file. I could telnet to the MySQL instance both from my Mac and from within the VM. So I knew the MySQL daemon was running and reachable. But when I tried to connect over JDBC, I got the “Communications link failure” error.

In my case, the problem was solved by editing the /etc/mysql/my.cnf file. Specifically, I commented out the “#bind-address=” line.

The Answer 9

2 people think this answer is useful

In case you are having problem with a set of Docker containers, then make sure that you do not only EXPOSE the port 3306, but as well map the port from outside the container -p 3306:3306. For docker-compose.yml:

version: '2'

        image: mariadb:10.1
            - "3306:3306"

The Answer 10

1 people think this answer is useful

For me the solution was to change in the conf file of mysql server the parameter bind-address=”″ or bind-address=”x.x.x.x” to bind-address=”″. Thanks.

The Answer 11

1 people think this answer is useful

I know this is an old thread but I have tried numerous things and fixed my issue using the following means..

I’m developing a cross platform app on Windows but to be used on Linux and Windows servers.

A MySQL database called “jtm” installed on both systems. For some reason, in my code I had the database name as “JTM”. On Windows it worked fine, in fact on several Windows systems it flew along.

On Ubuntu I got the error above time and time again. I tested it out with the correct case in the code “jtm” and it works a treat.

Linux is obviously a lot less forgiving about case sensitivity (rightly so), whereas Windows makes allowances.

I feel a bit daft now but check everything. The error message is not the best but it does seem fixable if you persevere and get things right.

The Answer 12

0 people think this answer is useful

It happens (in my case) when there is not enough memory for MySQL. A restart fixes it, but if that’s the case consider a nachine with more memory, or limit the memory taken by jvms

The Answer 13

0 people think this answer is useful

Go to Windows services in the control panel and start the MySQL service. For me it worked. When I was doing a Java EE project I got this error” Communication link failure”. I restarted my system and then it worked.

After that I again got the same error even after restarting my system. Then I tried to open the MySQL command line console and login with root, even then it gave me an error.

Finally when I started the MySQL service from Windows services, it worked.

The Answer 14

0 people think this answer is useful

Had the same. Removing port helped in my case, so I left it as jdbc:mysql://localhost/

The Answer 15

0 people think this answer is useful

If you are using hibernate, this error can be caused for keeping open a Session object more time than wait_timeout

I’ve documented a case in here for those who are interested.

The Answer 16

0 people think this answer is useful

I found the solution

since MySQL need the Localhost in-order to work.

go to /etc/network/interfaces file and make sure you have the localhost configuration set there:

auto lo
iface lo inet loopback

NOW RESTART the Networking subsystem and the MySQL Services:

sudo /etc/init.d/networking restart

sudo /etc/init.d/mysql restart

Try it now

The Answer 17

0 people think this answer is useful

It is majorly because of weak connection between mysql client and remote mysql server.

In my case it is because of flaky VPN connection.

The Answer 18

0 people think this answer is useful

In phpstorm + vagrant autoReconnect driver option helped.

The Answer 19

0 people think this answer is useful

The resolution provided by Soheil was successful in my case.

To clarify, the only change I needed to make was with MySQL’s server configuration;

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

I am using an external MySQL server for my application. It is a basic Debian 7.5 installation with MySQL Server 5.5 – default configuration.


Always backup the original of any configuration files you may modify. Always take care when elevated as super user.




bind-address        = #

Restart your MySQL Server service:

/usr/sbin/service mysql restart

As you can see, I simply provided the network IP of the server and commented out the default entry. Please note that simply copy and paste my solution will not work for you, unless by some miracle our hosts share the same IP.

Thanks @ Soheil

The Answer 20

0 people think this answer is useful

I was experiencing similar problem and the solution for my case was

  1. changing bind-address = from
  2. changing url’s localhost to localhost:3306

the thing i felt is we should never give up, i tried every options from this post and from other forums as well…happy it works @saurab

The Answer 21

0 people think this answer is useful

I faced this problem also.

As Soheil suggested, I went to php.ini file at the path C:\windows\php.ini , then I revised port number in this file.

it is on the line mysqli.default_port =……….

So I changed it in my java app as it’s in the php.ini file,now it works fine with me.

The Answer 22

0 people think this answer is useful

For Windows :- Goto start menu write , “MySqlserver Instance Configuration Wizard” and reconfigure your mysql server instance. Hope it will solve your problem.

The Answer 23

0 people think this answer is useful

After years having the same issue and no permanent solution this is whats solved it for the past 3 weeks (which is a record in terms of error free operation)

set global wait_timeout=3600;
set global interactive_timeout=230400;

Don’t forget to make this permanent if it works for you.

The Answer 24

0 people think this answer is useful

I just restarted MySQL (following a tip from here: and it solved the issue.

I had the same issue on MacOS (10.10.2) and MySql (5.6.21) installed via homebrew.

The confusing thing was that one of my apps connected to the database fine and the other did not.

After trying many things on the app that threw the exception com.mysql.jdbc.CommunicationsException as suggested by the accepted answer of this question to no avail, I was surprised that restarting MySQL worked.

The cause of my issue might have been the following as suggested in the answer in the aforementioned link:

Are you using connection pool ? If yes, then try to restart the server. Probably few of the connections in your connection pool are in closed state.

The Answer 25

-4 people think this answer is useful

If you are using local emulator, you have to use IP address instead of localhost to access to your local MySQL server.

Tags:, ,

Add a Comment