316

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?");
    }
}
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Josh K
  • 28,364
  • 20
  • 86
  • 132
  • 31
    I was a stupid. MySQL server was not started :( It was successful after starting it. – akfaisel Dec 27 '16 at 08:11
  • I changed my Springboot datasource from url: jdbc:mysql://XXX208465:localhost:3306/orv21_kafka_schema to url: jdbc:mysql://localhost:3306/orv21_kafka_schema. So the XXX208465 was not required which is my laptop's hostname. I installed mysql in local and am using it through mySQL CLI – raikumardipak Aug 25 '21 at 07:47
  • I am facing the same issue. On running "FLUSH HOSTS;" command it again starts connecting the server. But I dont want FLUSH HOSTS; rather find the root cause. Any leads? What can be the problem? – Suresh Huse Jun 27 '23 at 07:03

51 Answers51

323

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 4
    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
  • 8
    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 09: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 02 '16 at 08: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 02 '16 at 08:56
  • 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. – Abdul Mannan Jun 23 '17 at 08:03
  • One more reason, if u have ssl on mysql. I fixed it disable ssl or options in url connection. – Fortran Jun 23 '17 at 13:19
  • I use MAMP on MAC OS. It turns out the listening port is 8889. Just check http://localhost:8888/phpMyAdmin/index.php. The port shows in this page. In my case is Server: localhost:8889. I changed the code dataSource.setPortNumber(8889); Then the problem solved. – GoodApple Jul 08 '19 at 16:37
  • 1
    i had the same proble, i resolved it by changing the jdbc driver version and it worked just fine – Big Zed Dec 10 '19 at 22:19
25

In my case, the solution was to add the expected TLS protocol to the connection string like this:

jdbc:mysql://localhost:3306/database_name?enabledTLSProtocols=TLSv1.2

For testing/development purposes (not recommended for production) you can also try:

jdbc:mysql://localhost:3306/database_name?useSSL=false&allowPublicKeyRetrieval=true
Gerard de Visser
  • 7,590
  • 9
  • 50
  • 58
15

In my case, I needed to do a replacement of Localhost to the actual database server IP address

Instead of

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

I needed

 Connection con = DriverManager.getConnection(
 "jdbc:mysql://192.100.0.000:3306/DBname", "root", "root");
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
sureshAngamuthu
  • 191
  • 1
  • 2
  • 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 05 '18 at 16:00
  • 9
    This is the 'best solution' why? What problem does it solve, and how? – user207421 May 09 '18 at 22:09
  • this solution cannot generate dataframes – Alan Sep 24 '19 at 05:38
13

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.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
user1694306
  • 131
  • 1
  • 3
12

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.

Yogesh Funde
  • 767
  • 6
  • 13
11

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

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!

Nishi
  • 10,634
  • 3
  • 27
  • 36
shellbye
  • 4,620
  • 4
  • 32
  • 44
  • 5
    Unlikely. All these driver versions are supposed to be backwards-compatible. – user207421 Jan 20 '17 at 21:10
  • 1
    This issue seems to be fixed in new mysql connectors, see https://stackoverflow.com/questions/14559794/mysql-with-java-error-the-last-packet-sent-successfully-to-the-server-was-0-mil#comment20314498_14560182 – Nishi May 04 '19 at 16:45
  • The same case for me. The driver's version is for MySQL 5 while the server's version is 8. So I updated the jar's version and the problem solved. – edenPan May 04 '20 at 15:46
  • This worked like a wonder. Deserves more upvotes. I got to the point of scratching my head, but you saved me. Thank you so much. – Ch. Arham May 11 '22 at 17:01
9

Add this useSSL=false&allowPublicKeyRetrieval=true

jdbc:mysql://localhost:3306/cloudapp?useSSL=false&allowPublicKeyRetrieval=true

https://youtu.be/ray3YvnIohM

user7641341
  • 169
  • 1
  • 5
8

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);
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
7

This error may also happen if Java tries to connect to MySQL over SSL, but something goes wrong. (In my case, I was configuring Payara Server 5.193.1 connection pools to MySQL.)

Some people suggested setting useSSL=false. However, since Connector/J version 8.0.13, that setting is deprecated. Here's an excerpt from MySQL Connector/J 8.0 Configuration Properties:

sslMode

By default, network connections are SSL encrypted; this property permits secure connections to be turned off, or a different levels of security to be chosen. The following values are allowed: DISABLED - Establish unencrypted connections; PREFERRED - (default) Establish encrypted connections if the server enabled them, otherwise fall back to unencrypted connections; REQUIRED - Establish secure connections if the server enabled them, fail otherwise; VERIFY_CA - Like REQUIRED but additionally verify the server TLS certificate against the configured Certificate Authority (CA) certificates; VERIFY_IDENTITY - Like VERIFY_CA, but additionally verify that the server certificate matches the host to which the connection is attempted.

This property replaced the deprecated legacy properties useSSL, requireSSL, and verifyServerCertificate, which are still accepted but translated into a value for sslMode if sslMode is not explicitly set: useSSL=false is translated to sslMode=DISABLED; {"useSSL=true", "requireSSL=false", "verifyServerCertificate=false"} is translated to sslMode=PREFERRED; {"useSSL=true", "requireSSL=true", "verifyServerCertificate=false"} is translated to sslMode=REQUIRED; {"useSSL=true" AND "verifyServerCertificate=true"} is translated to sslMode=VERIFY_CA. There is no equivalent legacy settings for sslMode=VERIFY_IDENTITY. Note that, for ALL server versions, the default setting of sslMode is PREFERRED, and it is equivalent to the legacy settings of useSSL=true, requireSSL=false, and verifyServerCertificate=false, which are different from their default settings for Connector/J 8.0.12 and earlier in some situations. Applications that continue to use the legacy properties and rely on their old default settings should be reviewed.

The legacy properties are ignored if sslMode is set explicitly. If none of sslMode or useSSL is set explicitly, the default setting of sslMode=PREFERRED applies.

Default: PREFERRED

Since version: 8.0.13

So, in my case, setting sslMode=DISABLED was all I needed to resolve the issue. This was on a test machine. But for production, the secure solution would be properly configuring the Java client and MySQL server to use SSL.


Notice that by disabling SSL, you might also have to set allowPublicKeyRetrieval=true. (Again, not a wise decision from security standpoint). Further information is provided in MySQL ConnectionString Options:

AllowPublicKeyRetrieval

If the user account uses sha256_password authentication, the password must be protected during transmission; TLS is the preferred mechanism for this, but if it is not available then RSA public key encryption will be used. To specify the server’s RSA public key, use the ServerRSAPublicKeyFile connection string setting, or set AllowPublicKeyRetrieval=True to allow the client to automatically request the public key from the server. Note that AllowPublicKeyRetrieval=True could allow a malicious proxy to perform a MITM attack to get the plaintext password, so it is False by default and must be explicitly enabled.

Community
  • 1
  • 1
Sadeq Dousti
  • 3,346
  • 6
  • 35
  • 53
6

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.

Karl Walsh
  • 630
  • 7
  • 15
6

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
user3251882
  • 922
  • 1
  • 11
  • 21
  • 1
    This pointer solved my issue,specifying 'localhost' was working when I connect to VPN, but same was not working if I disconnect from VPN, however I fixed this by changing 'localhost' to '127.0.0.1' – gannu_lee May 05 '19 at 12:30
4

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.

rs2012
  • 81
  • 3
4

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

bind-address  = 0.0.0.0

Restart mysql deamon and mysql services.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Sreedhar GS
  • 2,694
  • 1
  • 24
  • 26
4

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" );
stacker
  • 68,052
  • 28
  • 140
  • 210
  • 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 06 '10 at 06:56
  • @Josh this works, you really just need to setup your classpath properly. (Or copy the jar into your %JAVA_HOME%\jre\lib\ext directory, but this is considered bad-practice) – stacker Jun 06 '10 at 07:15
3

My same problem is solved by the following steps:

  1. Go to my.cnf

    vi /etc/mysql/my.cnf
    
  2. Modify its bind-address

    "bind-address = 0.0.0.0"
    
  3. Restart MySQL

    sudo /etc/init.d/mysql restart
    
Shashanth
  • 4,995
  • 7
  • 41
  • 51
Haimei
  • 12,577
  • 3
  • 50
  • 36
2

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

xrcwrn
  • 5,339
  • 17
  • 68
  • 129
2

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

Erick G. Hagstrom
  • 4,873
  • 1
  • 24
  • 38
Maheshkumar.V
  • 77
  • 1
  • 8
2

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.

2

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.

MrPencil
  • 934
  • 8
  • 17
  • 36
2

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.

Haozhe Xie
  • 3,438
  • 7
  • 27
  • 53
2
dbhost=jdbc:mysql://172.18.23.100:3306/yourdatabase?useUnicode=yes&characterEncoding=UTF-8&useSSL=false
user=root
password=Password#321

con = DriverManager.getConnection(dbhost, user, password);

if mysql version 8 or higher user updated connector

Ravinath
  • 1,620
  • 1
  • 14
  • 8
2

In my case, turn out to be that the version of mysql-connector-java was different. I just changed mysql jdbc to maria jbdc

Old jdbc driver

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.21</version>
</dependency>


New Jdbc driver

<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
<dependency>
    <groupId>org.mariadb.jdbc</groupId>
    <artifactId>mariadb-java-client</artifactId>
    <version>2.6.2</version>
</dependency>

Adnan Asghar
  • 64
  • 1
  • 7
  • 1
    MariaDB is a fork of MySQL, but in effect they are two different databases. Your suggestion to use another JDBC driver is not a solution in this case, which was caused by the server not started up. – Joep Weijers Aug 25 '20 at 12:08
  • 1
    Thanks, but it worked for me after wasting many hours of no success. just thought to share with others. might be it can help and save time. – Adnan Asghar Aug 26 '20 at 07:41
  • Been at this for almost 1 hour now and this is the only thing that worked. Thanks @adnan – kopos Apr 29 '21 at 04:16
1

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.

mel3kings
  • 8,857
  • 3
  • 60
  • 68
1

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.

xrcwrn
  • 5,339
  • 17
  • 68
  • 129
Ankit Jain
  • 29
  • 1
1

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.

Michal Sipek
  • 536
  • 1
  • 6
  • 23
1

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 = 0.0.0.0
    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'
    
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Yugerten
  • 878
  • 1
  • 11
  • 30
1

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

`bind-address = 127.0.0.1

to

bind-address = 0.0.0.0 #this allows all systems to connect

Run below command in mysql for specific IP Address->

grant all privileges on dbname.* to dbusername@'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 dbusername@'%' IDENTIFIED BY 'dbpassword'; 
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Shiv Buyya
  • 3,770
  • 2
  • 30
  • 25
1

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.

10110
  • 2,353
  • 1
  • 21
  • 37
1

I have the same connection error: The problem I have is I used MySQL 8.0.15 but the Java Connector is 5.x.x.

Below is how I fixed it. 1. download the 8.0.15. from Maven repository: https://search.maven.org/search?q=g:mysql%20AND%20a:mysql-connector-java

  1. In the Eclipse IDE, select the "Referenced Libraries" in Explorer Right Mouse Button > Build Path > Configure Build Path a. remove the "mysql-connector-5.x.jar" b. Click "Add External JARs..." and select mysql-connector-java-8.0.15.jar.

Re-run it, the problem went away.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Peter Chen
  • 811
  • 6
  • 4
  • You really should be using Maven or Gradle to manage your dependencies, not the IDE. Similarly to how you don't manually add packages to your Python path – OneCricketeer Jan 03 '20 at 08:47
1

Sample jdbc connection class file. simply call the getConnection method when you want to get a connection. include related mysql-connector.jar

import java.sql.Connection;
import java.sql.DriverManager;


public class DBConnection {

    public Connection getConnection() {
        Connection con = null;

        String dbhost;
        String user;
        String password;
// get properties
dbhost="jdbc:mysql://localhost:3306/cardmaildb";
user="root";
password="123";

 System.out.println("S=======db Connecting======");

        try {
            Class.forName("com.mysql.jdbc.Driver");

            con = DriverManager.getConnection(dbhost, user, password);
            //if you are facing with SSl issue please try this 
            //con = DriverManager.getConnection("jdbc:mysql://192.168.23.100:3306/cardmaildb?useUnicode=yes&characterEncoding=UTF-8&useSSL=false",user, password);

        } catch (Exception e) {
            System.err.println("error in connection");
            e.printStackTrace();
        }
        System.out.println("E=======db Connecting======");
        return con;
    }

    public static void main(String[] args) {
        new DBConnection().getConnection();
    }
}
Ravinath
  • 1,620
  • 1
  • 14
  • 8
1

In my case, I faced this error when trying to connect to mysql-server running inside a container on a Ubuntu host VM from the same host.

Example: If my VM name is abc.company.com, the following jdbc URL would not work:

jdbc:mysql://abc.company.com:3306/dbname

Above jdbc url would work fine from other machines like xyz.company.com but just not abc.company.com.

where as the following jdbc URL would work just fine on abc.company.com machine:

jdbc:mysql://localhost:3306/dbname

which led me to check the /etc/hosts file.

Adding the following line to /etc/hosts fixed this issue:

127.0.1.1 abc.company.com abc

This seems to be an OS bug that requires us to add these on some Ubuntu versions. Reference: https://www.debian.org/doc/manuals/debian-reference/ch05.en.html#_the_hostname_resolution

Before trying this, I had tried all other solutions like GRANT ALL.., changing the bind-address line in mysql.cnf.. None of them helped me in this case.

A.R.K.S
  • 1,692
  • 5
  • 18
  • 40
1

This question has MANY answers, and I think mine would suit another question better, but the answers to that question are locked. It points to this thread.

What solved it for me was appending &createDatabaseIfNotExist=true to the spring.datasource.url string in application.properties.

This was very tricky because it manifested itself in a couple of different, weird, seemingly unrelated errors, and when I tried to fix what it complained about it simply would pop another error up, or the error was impossible to fix. It complained about not being able to load JDBC, saying it wasn't in the classpath, but I added it to the classpath in some 30 different ways and was already facedesking.

Pedro Queiroga
  • 381
  • 1
  • 12
1

I resolve this problem by downgrade jdk version. Downgrade from 11.0.11 to 11.0.10 or older java version

Thuan Tran
  • 351
  • 2
  • 7
1

I was facing this issue while running the automation tests on remote Jenkins server. However while running the tests on local no issue was occurring.

For me this issue was resolved after updating the mysql-connector version to the latest in the POM file as the MySQL version was changed on server side.

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

But debugging of the same turned out a bit difficult and took almost two days as I was not aware of the MySQL version change and it was working fine in local.

  • 1
    You just saved me a lot of debugging. I had the exact same situation and updating from "8.0.16" to "8.0.25" fixed it. Shame on mysql connector devs for breaking compatibility in a patch version. – Henry Parker Nov 24 '21 at 21:53
1

This problem is Create From xampp Port. First You should confirm your port number. Basically, everyone tries to use 3306 but sometimes it will be wrong. You can try this jdbc:mysql://127.0.0.1:3307

Musfiq Shanta
  • 1,298
  • 13
  • 9
1

Please use Platform Independent zip or tar, it works for me when encountering this error.

https://dev.mysql.com/downloads/connector/j/?os=26

Jackson
  • 71
  • 1
  • 6
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/30809724) – Procrastinator Jan 17 '22 at 08:14
1

Generally this problem occur, when database, which you use executing turn off in your OS. if you use windows then go to the services and make sure that MySQL is Starting positon.

1

In my case I was getting this error while running from intellij IDEA while running from terminal with ./gradlew bootRun was working fine. Then I figured out Intellij was pointing to some liberica java I'd downloaded. I changed it to OpenJdk one and it started working fine.

akib
  • 95
  • 6
1

In my case, Adding the query parameter in the connection String solved the issue. &useSSL=false

enter image description here

jdbc:mysql://${jdbc_url}:${jdbc_port}/${database_name}?serverTimezone=UTC&autoReconnect=true&useSSL=false&failOverReadOnly=false&maxReconnects=10

Sivaram Rasathurai
  • 5,533
  • 3
  • 22
  • 45
0

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.

Rey Libutan
  • 5,226
  • 9
  • 42
  • 73
0

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!

shivam gupta
  • 471
  • 5
  • 10
0

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.

Abdul Khalid
  • 174
  • 2
  • 13
0

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

hestellezg
  • 3,309
  • 3
  • 33
  • 37
0

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

m Piroli
  • 333
  • 3
  • 6
0

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.

Prakhar Agrawal
  • 153
  • 1
  • 6
0

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!

FullStack Alex
  • 1,783
  • 19
  • 31
0

There is a very special situation when this problem can happen, with MySQL Workbench, and especially when using the Eclipse JPA and persistence under localhost. The problem is that, as mentioned in some other answers, that the MySQL server can be very restrictive to using localhost, 0.0.0.0.1 or 127.0.0.1 when creating a connection. In order to overcome this, the hosts file in (for Windows):

C:\Windows\System32\drivers\etc

needs to have the following entry added to it for the main connection (e.g.myserver):

#MY DATABASE SERVER
127.0.0.1 myserver

If this is not added to hosts, the connection will fail every time you try to connect with the database from 127.0.0.1

keesp
  • 301
  • 2
  • 13
0

This can also happen why MySQL is dying. In my case I had a query that triggered a bug in MySQL and so the server died and restarted whenever the query was executed. Look in your MySQL error log to see if that's happening. In my case (Homebrew on MacOS) that was in /usr/local/var/mysql/<machinename>.err

Since I was seeing this on a test system I ended up dropping and recreating my database which solved the problem but I dread to think what I would have done if it was on production.

mjaggard
  • 2,389
  • 1
  • 23
  • 45
0

I just want to add another answer because it is not always a problem in your backend configuration or connections pool, etc.

Sometimes it is also the infrastructure of your database, the location of the server where it is at, so make sure that you have a good database infrastructure (cpu, ram, network, etc.) and also that it is on the same region of your application, this way you will improve alot the performance and stop getting this error messages that in some cases as I am trying to explain, is more about your database

BugsOverflow
  • 386
  • 3
  • 19
-1

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

aclowkay
  • 3,577
  • 5
  • 35
  • 66
-2

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.