0% found this document useful (0 votes)
538 views

Java - Solving A "Communications Link Failure" With JDBC and MySQL - Stack Overflow

The document describes a "communications link failure" error when trying to connect to a local MySQL database from a Java application. It provides the code showing how the connection is established and the specific error messages. Several potential solutions are listed that have worked for other users, such as checking that the MySQL server is running, reviewing connection string parameters and MySQL configuration settings. The key is to try the different solutions systematically to find what resolves the issue for your specific situation.

Uploaded by

Shadman Alam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
538 views

Java - Solving A "Communications Link Failure" With JDBC and MySQL - Stack Overflow

The document describes a "communications link failure" error when trying to connect to a local MySQL database from a Java application. It provides the code showing how the connection is established and the specific error messages. Several potential solutions are listed that have worked for other users, such as checking that the MySQL server is running, reviewing connection string parameters and MySQL configuration settings. The key is to try the different solutions systematically to find what resolves the issue for your specific situation.

Uploaded by

Shadman Alam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

sign up

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration
required.

log in

tour

help

careers 2.0

Take the 2-minute tour

Solving a communications link failure with JDBC and MySQL


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";
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) {}
}
}
}
}
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
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl
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
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
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
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl
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
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)
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.
java

mysql

jdbc

edited May 18 at 15:53


Tiny
2,268 15 79 185

asked Jul 28 '11 at 20:55


Anthony
113 1 1 7

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? Jim Garrison Jul 28 '11 at
20:59
Check this post. Might help: stackoverflow.com/questions/15949/ maclema Jul 28 '11 at 21:07
Problem solved, added a bind-address entry to my.cnf. Anthony Jul 28 '11 at 21:28
What address did you put for your bind-address? prolink007 Oct 11 '11 at 21:45

@Anthony You should put your comment as an answer and accept it ... Fildor Nov 1 '11 at 17:24

show 2 more comments

17 Answers
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
I spend some 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.
point: For the solutions that you need to change the MySQL settings, you can refer to the following not:
Linux: /etc/mysql/my.cnf
Windows: D:\Program Files\mysql\bin\my.ini

Here are 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 = 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
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&cha


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

Although non of these solutions worked for me, I suggest you to try them. Because there are some people
how 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
created connection and then closed it. Although I closed 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.

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.
edited May 7 at 16:39
youssefhassan
686 1 6 11

answered May 27 '12 at 7:40


Soheil
761 4 13

Gud soheil. Its work for me when i connect in network. Thanks RED.Skull Jan 29 '13 at 7:06
I added wait_timeout only, referred to dev.mysql.com/doc/refman/5.1/en/ Siddharth Apr 4 '13 at 22:06

Where are the variables TOMCAT6_SECURITY and validationQuery ? Thanks! Charles Wood Mar 27
at 17:03
add a comment

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.
edited Sep 30 '12 at 14:46

answered Sep 20 '12 at 15:41


fuoco
11 2

add a comment

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
answered May 27 '12 at 7:47
Bozho
273k 39 514 713
add a comment

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.
edited Mar 10 '13 at 9:39

Arjan Tijms
21.6k 6 49 83
add a comment

answered Mar 6 '13 at 7:34

tinku
177 3 17

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


answered Mar 17 '13 at 19:24
user2180110
1
add a comment

Setting the bind-address to the server's network IP instead of the localhost default, and setting
privileges on my user worked for me.
my.cnf:
bind-address = 192.168.123.456
MySql Console:
GRANT ALL PRIVILEGES ON dbname.* to username@'%' IDENTIFIED BY 'password';
answered Apr 3 '13 at 21:14
Kevin Lawrence
516 4 13
add a comment

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.
answered Sep 3 '13 at 16:01
Raul Luna
170 2 9
add a comment

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
answered Sep 13 '13 at 11:54
Mahmoud Zalt
62 1 7
doesn't work on Mac Air Jun 29 at 9:57
not sure about Mac, this worked for me on Linux Debian. Mahmoud Zalt Jun 30 at 14:51

Ok. This worked after changing MySQL port and connecting to that new port. Air Jul 1 at 0:26

add a comment

It is majorly because of weak connection between mysql client and remote mysql server.
In my case it is because of flaky VPN connection.
answered Oct 4 '13 at 18:15
Ankit Singhal
151 3
add a comment

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=127.0.0.1" line.
answered Feb 12 at 2:57
devdanke
464 3 11
add a comment

In phpstorm + vagrant autoReconnect driver option helped.


answered Feb 18 at 5:25
gaRex
2,402 9 20
got: java.sql.SQLException: Could not create connection to database server. Attempted reconnect 3 times.
Giving up. Air Jun 29 at 9:57
add a comment

If you are using local emulator, you have to use IP address 10.0.2.2 instead of localhost to access to your
local MySQL server.
answered Mar 7 at 11:05
Carlos
6 1
add a comment

I've just faced the same problem. It happened because the MySQL Daemon was binded to the IP of the

machine, which makes 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 changes in my.cnf to
bind-address = MY_IP_ADDRESS
To fix the issue I changed to
bind-address = 0.0.0.0
Which will allow a users from localhost AND even outside (in my case). Both below permissions will work if
you bind the MySQL to 0.0.0.0:
USER_NAME@MACHINE_NAME_OR_IP
USER_NAME@localhost
answered Mar 19 at 4:28
Renann
18 5
add a comment

In my case,
1. Change the remote machine mysql configuration at /etc/mysql/my.cnf : change bindaddress = 127.0.0.1 to #bind-address = 127.0.0.1
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
answered May 13 at 19:39
cindyxiaoxiaoli
91 3
add a comment

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.
IMPORTANT:
Always backup the original of any configuration files you may modify. Always take care when
elevated as super user.
File
/etc/mysql/my.cnf
Line
bind-address

= 192.168.0.103 #127.0.0.1

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
answered May 18 at 4:46
user3648959
1
add a comment

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

1. changing bind-address = 0.0.0.0 from 127.0.0.1


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
answered Jul 3 at 18:20
Saurab Dulal
1 2
add a comment

For me the solution was to change in the conf file of mysql server the parameter bind-address="127.0.0.1"
or bind-address="x.x.x.x" to bind-address="0.0.0.0". Thanks.
answered yesterday
user1969545
11 1
add a comment

Not the answer you're looking for? Browse other questions tagged java mysql jdbc
or ask your own question.

You might also like