By Josh K


2010-06-06 05:49:10 8 Comments

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?");
    }
}

30 comments

@Daniel Segura 2019-02-10 15:30:37

I was receiving multiple errors such as:

  • CommunicationsException: Communications link failure
  • java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()' on a null object reference at.

I had to add:

  • In AndroidManifest.xml include <uses-permission android:name="android.permission.INTERNET"/> just after the opening manifest tag.

  • Add the JDBC driver into your Gradle (or Maven) dependencies.

@Chase Owens 2019-01-22 22:08:41

Also your server might just be closed. On a Mac, navigate to mySQL preference panel through the spotlight. When there, check the box to start your server when your computer starts and start the server.

@Tech Nomad 2018-12-23 01:44:15

In my case I had to establish an ssh tunnel to the remote database and all the settings were correct and testing the connection with PhpStorm were also successful. And also the schema was loaded, but not the data. Instead I got:

[08S01] 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.

No of the suggestions above worked. For any reason I tried to solve the problem by simply restarting PhpStorm and voila it worked!

@ShivBuyya 2018-11-17 06:18:36

Open file /etc/mysql/my.cnf: change below parameter from

bind-address = 127.0.0.1 to bind-address = 192.168.0.3 #this is your local system IP Address,

Run below command in mysql for specific IP Address->

grant all privileges on dbname.* to [email protected]'192.168.0.3' IDENTIFIED BY 'dbpassword';                      

If you want to give access to all IP Address, run below command:

grant all privileges on dbname.* to [email protected]'%' IDENTIFIED BY 'dbpassword'; 

@Yugerten 2018-11-07 21:06:19

For Remote Call to Mysql

  1. Add remote user to Mysql from for exemple IP=remoteIP :

    mysql -u xxxx -p //local coonection to mysql
    mysql> GRANT ALL PRIVILEGES ON *.* TO 'theNewUser'@'remoteIP' IDENTIFIED BY 'passWord';
    //Query OK, 0 rows affected (xx sec)
    mysql> FLUSH PRIVILEGES;
    //Query OK, 0 rows affected
    
  2. Allow remote access to Mysql (by default all externall call is not allowed):

    Edit 
    /etc/mysql/mysql.conf.d/mysqld.cnf    or    /etc/mysql/my.cnf
    Change line:  bind-address = 127.0.0.1   to
                  #bind-address = 127.0.0.1
    Restart Mysql: /etc/init.d/mysql restart
    
  3. For The latest version of JDBC Driver, the JDBC :

    jdbc.url='jdbc:mysql://remoteIP:3306/yourDbInstance?autoReconnect=true&amp;useUnicode=true&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC'
    jdbc.user='theNewUser'
    

@Prakhar Agrawal 2018-11-03 06:54:50

I was facing the same problem while i was starting my application,

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.

The issue was that in the mysql file /etc/mysql/mysql.conf.d/mysqld.cnf, the configuration was like that

[mysqld]
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
datadir         = /var/lib/mysql
log-error       = /var/log/mysql/error.log
# By default we only accept connections from localhost
bind-address    = 127.0.0.1
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

So as we can see that bind address is pointing to the 127.0.0.1, so for starting your application, a simple solution is that we can use the jdbc:mysql://127.0.0.1:3306/pizzeria instead of jdbc:mysql://localhost:3306/pizzeria which will connect the mysql to the application or another solution is that you can check and change the mysql configurations to default.Both solution can work. I hope it will work for you guys too.

@m Piroli 2018-10-24 15:15:53

In my MacBook i have solvet this error only when reinstall the new version of eclipse EE and remove local servers like xamp mysql or mamp but use only one of them ...

@Michal Šípek 2018-06-07 06:17:20

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.

@hestellez 2018-02-12 23:07:13

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 iscom.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

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

@Abdul Khalid 2017-08-16 08:06:43

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.

@shivam gupta 2017-07-23 16:04:46

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!

@Haozhe Xie 2017-05-18 01:24:51

Try to change localhost to 127.0.0.1.

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

And here is the output of 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.

@user3251882 2016-12-22 10:36:40

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.

@Sreedhar GS 2014-04-12 19:07:58

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

bind-address  = <IP_ADDRESS>

Restart mysql deamon and mysql services.

@aclokay 2016-12-28 13:11:34

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

@BalusC 2010-06-06 17:40:40

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:

  1. IP address or hostname in JDBC URL is wrong.
  2. Hostname in JDBC URL is not recognized by local DNS server.
  3. Port number is missing or wrong in JDBC URL.
  4. DB server is down.
  5. DB server doesn't accept TCP/IP connections.
  6. DB server has run out of connections.
  7. Something in between Java and DB is blocking connections, e.g. a firewall or proxy.

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

  1. Verify and test them with ping.
  2. Refresh DNS or use IP address in JDBC URL instead.
  3. Verify it based on my.cnf of MySQL DB.
  4. Start the DB.
  5. Verify if mysqld is started without the --skip-networking option.
  6. Restart the DB and fix your code accordingly that it closes connections in finally.
  7. Disable firewall and/or configure firewall/proxy to allow/forward the port.

See also:

@Jurik 2013-09-25 13:46:27

MAMP/ MAMP Pro sets MAMP_skip-networking_MAMP by default. You've to disable this line in your my.cfn

@nikel 2015-12-19 09:24:00

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"

@Farhad 2016-09-02 08:34:11

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

@nikel 2016-09-02 08:56:53

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

@Hammad Tariq 2017-04-19 10:55:28

Disabling windows firewall worked for me.

@Abdul Mannan 2017-06-23 08:03:55

Sometimes port is missing from connection string & driver will try to connect to default 3306 mysql port & fail if mysql isn't running at this port. It was my issue so i though i should mention in case somebody else will find it useful.

@Fortran 2017-06-23 13:19:45

One more reason, if u have ssl on mysql. I fixed it disable ssl or options in url connection.

@Maheshkumar.V 2014-11-13 10:05:05

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

@shellbye 2015-07-02 02:54:08

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

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

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

@user207421 2017-01-20 21:10:01

Unlikely. All these driver versions are supposed to be backwards-compatible.

@MrPencil 2015-05-15 10:08:40

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.

@Abdul Rahim Mohamad 2015-04-30 02:16:21

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

@DAVIS BENNY 15MIS0426 2018-07-20 12:35:55

if you have mamp before install Mysql then try this method

@Dario Castro 2015-04-16 15:20:06

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.

@Yogesh Funde 2015-02-26 09:22:50

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.

@user207421 2018-05-09 22:09:38

It also occurs for other reasons such as 'connection refused'.

@Haimei 2014-06-02 18:54:53

My same problem is solved by following steps:

  1. go to my.cnf

    vi /etc/mysql/my.cnf

  2. modify its bind-address

    "#bind-address = 127.0.0.1"

  3. restart mysql

    sudo /etc/init.d/mysql restart

@sureshAngamuthu 2014-03-12 10:32:07

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

@Abhishek Ekaanth 2018-04-05 16:00:43

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.

@user207421 2018-05-09 22:09:03

This is the 'best solution' why? What problem does it solve, and how?

@Ankit Jain 2014-11-04 05:10:03

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.

@Kiran Nunna 2015-05-17 14:43:42

Yes there can be chance of jar mismatch.

@user207421 2017-01-20 21:12:44

All these driver versions are supposed to be compatible.

@xrcwrn 2014-11-04 05:19:02

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

@user3427633 2014-03-17 05:34:49

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

  1. My .jsp was calling attributes that I had not yet defined in the servlet.
  2. I had two column names that I was passing into an object through ResultSet (getString("columnName")) that didn't match the column names in my database.

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.

@user207421 2018-05-09 22:11:10

(1) certainly does not cause this problem.

@user1694306 2013-05-16 18:20:20

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.

@mel3kings 2013-05-12 06:59:18

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.

@user207421 2017-01-20 21:07:41

The static block hasn't been necessary since 2007, and you can specify the login parameters either way.

@rs2012 2013-04-04 04:53:55

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.

Related Questions

Sponsored Content

0 Answered Questions

4 Answered Questions

[SOLVED] Mysql Drop Table as PreparedStatement not working for me

2 Answered Questions

1 Answered Questions

[SOLVED] JDBC MySQL query syntax

  • 2017-05-23 01:36:21
  • Ivan M
  • 316 View
  • 1 Score
  • 1 Answer
  • Tags:   java mysql jdbc

0 Answered Questions

Multithread instance of mysql error

  • 2017-02-26 17:09:58
  • toto
  • 38 View
  • 0 Score
  • 0 Answer
  • Tags:   java mysql

1 Answered Questions

MYSQL & SQuirreL - Unexpected Error occurred attempting to open an SQL connection

  • 2016-01-19 02:38:11
  • Fenn Cris
  • 927 View
  • 0 Score
  • 1 Answer
  • Tags:   java mysql sql jdbc

1 Answered Questions

[SOLVED] PHPStorm doesn't connect to local MySQL

  • 2015-08-06 19:53:15
  • Aerendir
  • 1370 View
  • 0 Score
  • 1 Answer
  • Tags:   mysql macos jdbc

3 Answered Questions

[SOLVED] Cannot connect to mysql database from VM using java

  • 2015-07-21 08:19:11
  • Florina
  • 1024 View
  • 1 Score
  • 3 Answer
  • Tags:   java mysql wamp

2 Answered Questions

[SOLVED] Connect to a user input database

  • 2015-03-24 20:16:46
  • Andrei Maieras
  • 1290 View
  • 1 Score
  • 2 Answer
  • Tags:   java mysql

Sponsored Content