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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



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



I'm working on getting my database to talk to my Java programs.



Can someone give me a quick and dirty sample program using the JDBC?



I'm getting a rather stupendous error:


Exception in thread "main" 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:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2260)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:787)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49)
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:409)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:357)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at SqlTest.main(SqlTest.java:22)
Caused by: 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:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2181)
... 12 more
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
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:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:293)
... 13 more



Contents of the test file:


import com.mysql.jdbc.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SqlTest

public static void main(String args) throws Exception
// Class.forName( "com.mysql.jdbc.Driver" ); // do this in init
// // edit the jdbc url
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/projects?user=user1&password=123");
// Statement st = conn.createStatement();
// ResultSet rs = st.executeQuery( "select * from table" );

System.out.println("Connected?");






I was a stupid. MySQL server was not started :( It was successful after starting it.
– user2589739
Dec 27 '16 at 8:11




26 Answers
26



So, you have a



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

java.net.ConnectException: Connection refused



I'm quoting from this answer which also contains a step-by-step MySQL+JDBC tutorial:



If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException:
Communications link failure
, then it means that the DB isn't reachable at all. This can have one or more of the following causes:


SQLException: Connection refused


Connection timed out


CommunicationsException:
Communications link failure



To solve the one or the other, follow the following advices:


ping


my.cnf


--skip-networking option


finally





MAMP/ MAMP Pro sets MAMP_skip-networking_MAMP by default. You've to disable this line in your my.cfn
– Jurik
Sep 25 '13 at 13:46





Not in this case, but a Communications Link Failure also happens when you are using a connection Pool and the connections are closed due to prolonged inactivity. Only in that case , it says "Last packet was recieved some "X" seconds ago"
– nikel
Dec 19 '15 at 9:24





@nikel Shouldn't the threads in the connection pool be kept active by firing the "select 1" validation query? Why would they get closed by prolonged inactivity when we have set the evictor to run at shorter time intervals than the mysql server timeout?
– Farhad
Sep 2 '16 at 8:34





Yes, a validation query would fix this. My point was about the case when it is not set & connections in the pool get timed out due to inactivity
– nikel
Sep 2 '16 at 8:56





Disabling windows firewall worked for me.
– Hammad Tariq
Apr 19 '17 at 10:55



I catch this exception when Java out of heap. If I try to put in RAM many data items - first I catch "Communications link failure" and next "OutOfMemoryError".



I logged it and I decrease memory consumption (delete 1/2 data) and all ok.



I might be barking up the wrong tree here, but your exception seems to indicate your MySQL server isn't available.



Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failureThe last packet sent successfully to the server was 0
milliseconds ago. The driver has not received any packets from the server. at...



What happens if you try (from the terminal)


mysql -u username -p



You will be prompted for the password associated with the username. After you give the correct password does the mysql client connect?



You may have to start MySQL from the Preferences if not. You can also set it to run at startup.





I'm using MAMP to run my MySQL server. Would that be an issue?
– Josh K
Jun 6 '10 at 17:02





When I connect (via Sequal Pro) to my localhost I use the correct username / password and it works fine.
– Josh K
Jun 6 '10 at 17:03


localhost



This com.mysql.jdbc.exceptions.jdbc4.CommunicationsException exception occurs if your database connection is idle for long time.


com.mysql.jdbc.exceptions.jdbc4.CommunicationsException



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.


connection.isClosed();





It also occurs for other reasons such as 'connection refused'.
– user207421
May 9 at 22:09



I've been having the same problem for hours. I'm using MAMP Server



Instead of using localhost:[Apache Port], use your MySQL port.



Below is the default MySQL Port for MAMP server.


String url = "jdbc:mysql://localhost:8889/db_name";

Connection conn = DriverManager.getConnection(url, dbUsername, dbPassword);





if you have mamp before install Mysql then try this method
– DAVIS BENNY 15MIS0426
Jul 20 at 12:35



This is best solution,


Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/DBname", "root", "root");

Connection con = DriverManager.getConnection(
"jdbc:mysql://192.100.0.000:3306/DBname", "root", "root");



Replacement of Localhost to your IP address





On Latest Update 4/5/18 : Currently, I'm using MySQL Workbench 6.3. I came here to check the solution but I found it on my own, it's just that your MySQL server is not running or it is stopped. I restarted my server it worked like a charm.
– Abhishek Ekaanth
Apr 5 at 16:00





This is the 'best solution' why? What problem does it solve, and how?
– user207421
May 9 at 22:09



Download MySQL-JDBC-Type-4-Treiber (i.g. 'mysql-connector-java-5.1.11-bin.jar' from 'mysql-connector-java-5.1.11.zip') at Mysql.



You need to inculde the driver jar during compile- and runtime in your classpath.


Class.forName( "com.mysql.jdbc.Driver" ); // do this in init
// edit the jdbc url
Connection conn = DriverManager.getConnection( "jdbc:mysql://MyDbComputerNameOrIP:3306/myDatabaseName", username, password );
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery( "select * from table" );





Nope, gives me a storm of errors about not finding anything. Would it be possible to import this without the JAR file?
– Josh K
Jun 6 '10 at 6:56





@Josh this works, you really just need to setup your classpath properly. (Or copy the jar into your %JAVA_HOME%jrelibext directory, but this is considered bad-practice)
– stacker
Jun 6 '10 at 7:15



I got the same error because I was trying to run my program without starting mysql server.



After starting the mysql server, everything went right.



Please update your IP address in /etc/mysql/my.cnf file


bind-address = <IP_ADDRESS>



Restart mysql deamon and mysql services.





Please update this why?
– user207421
Jan 20 '17 at 21:06



Earlier answers are appropriate . But , I would also like to point towards a more generic issue.



I faced similar issue and the reason was a network restriction of my company.



Same connection was getting successful when I was in any other network.



Just experienced this.



Got to make it work by:
(this can be placed in the static block intializer)


static // would have to be surrounded by try catch
Class.forName("com.mysql.jdbc.Driver"); // this will load the class Driver



Also by obtaining the connection through:


conn = DriverManager.getConnection(DBURL,<username>,<password>);



instead of specifying the login parameters


Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/projects?user=user1&password=123");



Regards.





The static block hasn't been necessary since 2007, and you can specify the login parameters either way.
– user207421
Jan 20 '17 at 21:07



If you are using WAMP or XAMP server to install mysql database.
Then you have to explicitly start mysql sever other wise it will show
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure while connecting with database


WAMP


XAMP


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



My same problem is solved by following steps:



go to my.cnf



vi /etc/mysql/my.cnf


vi /etc/mysql/my.cnf



modify its bind-address



"#bind-address = 127.0.0.1"


"#bind-address = 127.0.0.1"



restart mysql



sudo /etc/init.d/mysql restart


sudo /etc/init.d/mysql restart



i solved this problem in a easy way, that worked for me. i had the seme problem "com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure". In my db.properties file i had this : url:jdbc:mysql://localhost:90/myDB,
only removed the port url , resulting in this manner url:jdbc:mysql://localhost/myDB and that worked for me.



Thats happened to me when I changed the mysql port from 3306 to 3307 in my.ini and the php.ini files but after changing the ports (3307->3306) back it worked fine again.



In my case, turn out to be that the version of mysql-connector-java was to high.


mysql-connector-java



In my demo, I somehow use mysql-connector-java like this:


mysql-connector-java


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



But in the develop environment, I use this:


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



And my MySQL version was 5.1.48(yes, it is old, just for mimic the product version). So I met the same error.



Since the reason is found, the solution is found, too. Match the version!





Unlikely. All these driver versions are supposed to be backwards-compatible.
– user207421
Jan 20 '17 at 21:10



If you changed your port, you get this kind of error "com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure"
Please check your port number



I had the same problem, and here's how it was fixed:


ResultSet (getString("columnName"))



I'm not exactly sure which one fixed the problem, but it worked. Also, be sure that you create a new Statement and ResultSet for each table query.


Statement


ResultSet





(1) certainly does not cause this problem.
– user207421
May 9 at 22:11



It could be a simple jar problem. may be you are using a old mysql-connector-java-XXX-bin.jar which is not supported by your current mysql version. i used mysql-connector-java-5.1.18-bin.jar as i am using mysql 5.5 and this problem is resolved for me.


mysql-connector-java-XXX-bin.jar


mysql-connector-java-5.1.18-bin.jar


mysql 5.5





Yes there can be chance of jar mismatch.
– Kiran Nunna
May 17 '15 at 14:43





All these driver versions are supposed to be compatible.
– user207421
Jan 20 '17 at 21:12



Try to change localhost to 127.0.0.1.


localhost


127.0.0.1



The localhost would be resolved to ::1. And MySQL cannot be connected via IPv6 by default.


::1



And here is the output of telnet localhost 3306:


telnet localhost 3306


$ telnet localhost 3306
Trying ::1...



And there is no response from MySQL server.



Of course, please make sure your MySQL server is running.



What solved for me is doing 2 thing:
1. create new user other than root with some password using following connads:


CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost';
FLUSH PRIVILEGES;



2. comment IP address line on mysqld.conf



then connect with new username and password. it should work.



It was trying to connect to an older version of MySQL ('version', '5.1.73'
); when you use a newer driver version you get an error that tells you to use the "com.mysql.cj.jdbc.Driver or even that you don't have to especify which one you use:



Loading class com.mysql.jdbc.Driver'. This is deprecated. The new
driver class is
com.mysql.cj.jdbc.Driver'. The driver is
automatically registered via the SPI and manual loading of the driver
class is generally unnecessary.


com.mysql.jdbc.Driver'. This is deprecated. The new
driver class is



I changed the declaration to use 5.1.38 version of the mysql-connector-java and, in the code, I kept the com.mysql.jdbc.Driver.


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



All started when I saw the Ankit Jain's answer



My firewall was blocking post 3307 which my MySQL listening on. So I changed port from 3307 to 3306.Then I can successfully connect to a database.



If there are any readers who encountered this issue for accessing remote server: make sure the port is open



Maybe you did not start your Mysql and Apache Server. After I started Apache server and Mysql from XAMPP Control Panel, connection was successfully established.



Good luck!



I faced the same issue on IntelliJ IDEA.



To solve the connection problem, I had to disconnect (+F2 using default keybindings on a mac) and reconnect again. Just pressing "refresh" was not enough.




Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



Would you like to answer one of these unanswered questions instead?

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard