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?");
}
}
My same problem is solved by the following steps:
Go to my.cnf
vi /etc/mysql/my.cnf
Modify its bind-address
"bind-address = 0.0.0.0"
Restart MySQL
sudo /etc/init.d/mysql restart
Please update your IP address in /etc/mysql/my.cnf file
bind-address = 0.0.0.0
Restart mysql deamon and mysql services.
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.
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
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);
I see you are connecting to a remote host. Now the question is what type of a network are you using to connect to the internet?
WINDOWS
If it's a mobile broadband device then get your machines IP address and add it to your hosting server so that your host server can allow connections coming from your machine.[your host might have turned this off due to security reasons]. Note that every time you use a different network device your IP changes.
If you are using a LAN then set a static IP address on your machine then add it to your host.
I hope this helps!! :)
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>
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.
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.
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';
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.
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!
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
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.
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.
This is a wrapped exception and not really interesting. It is the root cause of the exception which actually tells us something about the root cause. Please look a bit further in the stacktrace. The chance is big that you'll then face a SQLException: Connection refused
or SQLException: Connection timed out
.
If this is true in your case as well, then all the possible causes are:
To solve the one or the either, follow the following advices:
ping
.my.cnf
of MySQL DB.--skip-networking
option.By the way (and unrelated to the actual problem), you don't necessarily need to load the JDBC driver on every getConnection()
call. Just only once during startup is enough.
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.
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.
I've been having this issue also for about 8-9 days. Here's some background: I'm developing a simple Java application that runs in bash.
Details:
[jvazquez@archbox ~]$ mysql --version mysql Ver 14.14 Distrib 5.5.9, for Linux (i686) using readline 5.1 Linux archbox 2.6.37-ARCH #1 SMP PREEMPT Fri Feb 18 16:58:42 UTC 2011 i686 Intel(R) Core(TM)2 Quad CPU Q8200 @ 2.33GHz GenuineIntel GNU/Linux
The application works fine in Arch Linux, Mac OS X 10.6, and FreeBSD 7.2. When I moved the jar file to another arch linux in a different host, using the same mysql, a similar my.cnf, and the similar kernel version, the connection died and obtained the same error as the original poster:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
I tried every possible combination for this that I found on so and the forums (http://forums.mysql.com/read.php?39,180347,180347#msg-180347 for example, which is closed now and I can't post .. ), specifically:
As it was pointed out (if you look up for the same exception , you will find several so threads about the issue Reproduce com.mysql.jdbc.exceptions.jdbc4.CommunicationsException with a setup of Spring, hibernate and C3P0 for example ).
If the link get's removed, just add mysqld:ALL to /etc/hosts.allow
I know that is a bit extense, but it may help anybody using GNU/Linux and having this exception and this thread seemed the best place to post my research.
Hope it helps
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.
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();
}
}
In my case, the local loopback interface wasn't started, so "localhost" couldn't be resolved. You can check this by running "ifconfig" and you should see an interface called "lo". If it is not up, you can activate it by running "ifup lo" or "ifconfig lo up".
If you use WAMP, make sure it is online. What I did was, first turned my firewall off, then it worked, so after that I allowed connection for all local ports, specially port 80. Than I got rid of this problem. For me it was the Firewall who was blocking the connection.
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 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
Re-run it, the problem went away.
We have a piece of software (webapp with Tomcat) using Apache commons connection pooling, and worked great for years. In the last month I had to update the libraries due to an old bug we were encountering. The bug had been fixed in a recent version.
Shortly after deploying this, we started getting exactly these messages. Out of the thousands of connections we'd get a day, a handful (under 10, usually) would get this error message. There was no real pattern, except they would sometimes cluster in little groups of 2 to 5.
I changed the options to on the pool to validate the connection every time one is taken from or put back in the pool (if one is found bad, a new one is generated instead) and the problem went away.
Have you updated your MySQL jar lately? It seems like there may be a new setting that didn't used to be there in our (admittedly very old) jar.
I agree with BalusC to try some other options on your config, such as those you're passing to MySQL (in addition to the connection timeout).
If this failure is transient like mine was, instead of permanent, then you could use a simple try/catch and a loop to keep trying until things succeed or use a connection pool to handle that detail for you.
Other random idea: I don't know what happens why you try to use a closed connection (which exception you get). Could you be accidentally closing the connection somewhere?
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.
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 ...
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.
Ensure skip-networking is commented out in my.cnf/my.ini
I had the same problem, and here's how it was fixed:
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.
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.
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" );
I encountered same problem. I am using spring & dbcp & mysql 5.5But If I change localhost
to 192.168.1.110
then everything works. What make things more weird is mysql -h localhost
just works fine.
update: Finally found a solution. Changing bindaddress to localhost
or 127.0.0.1
in my.conf
will fix the problem.
As BalusC mentioned, it would be very useful to post the full stacktrace (always post a full stacktrace, it is useless and frustrating to have only the first lines of a stacktrace).
Anyway, you mentioned that your code was working fine and that this problem started suddenly to occur without any code change so I'm wondering if this could be related to you other question Problem with not closing db connection while debugging? Actually, if this problem started while debugging, then I think it is (you ran out of connections). In that case, restart you database server (and follow the suggestions of the other question to avoid this situation).
In my case, the mysql.com downloaded Connector/J 5.1.29 .jar had this error whereas the 5.1.29 .jar downloaded from the MvnRepository did not.
This happened when building a Google appengine application in Android Studio (gradle, Windows x64), communicating to a Linux MySQL server on the local network/local VM.
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
For Remote Call to Mysql
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
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
For The latest version of JDBC Driver, the JDBC :
jdbc.url='jdbc:mysql://remoteIP:3306/yourDbInstance?autoReconnect=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC'
jdbc.user='theNewUser'
check your wait timeout set on the DB server. Some times it defaults to 10 seconds. This looses the connection in 10 seconds.
mysql> show global variables like '%time%' ;
update it make it something like 28800
mysql> SET GLOBAL wait_timeout = 28800;
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.
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
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");
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!
The escential problem is that Mysql JDBC pool connections is not used, then the Timeout from Mysql, close the Connections. You need change the pool Parameters to get restart connection when the connection has failures, on this way:
Connection Validation
: Required (Check)
Validation Method:
autocommit
You can change the Validation Method if you cannot get it works!
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.
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.
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
- LikeREQUIRED
but additionally verify the server TLS certificate against the configured Certificate Authority (CA) certificates;VERIFY_IDENTITY
- LikeVERIFY_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
, andverifyServerCertificate
, which are still accepted but translated into a value forsslMode
ifsslMode
is not explicitly set:useSSL=false
is translated tosslMode=DISABLED
;{"useSSL=true", "requireSSL=false", "verifyServerCertificate=false"}
is translated tosslMode=PREFERRED
;{"useSSL=true", "requireSSL=true", "verifyServerCertificate=false"}
is translated tosslMode=REQUIRED
;{"useSSL=true" AND "verifyServerCertificate=true"}
is translated tosslMode=VERIFY_CA
. There is no equivalent legacy settings forsslMode=VERIFY_IDENTITY
. Note that, for ALL server versions, the default setting ofsslMode
isPREFERRED
, and it is equivalent to the legacy settings ofuseSSL=true
,requireSSL=false
, andverifyServerCertificate=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 ofsslMode
oruseSSL
is set explicitly, the default setting ofsslMode=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 theServerRSAPublicKeyFile
connection string setting, or setAllowPublicKeyRetrieval=True
to allow the client to automatically request the public key from the server. Note thatAllowPublicKeyRetrieval=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.
I got the same error but then I figured it out its because the Mysql server is not running at that time.
So to change the status of the server
Hope this will help.
I had the same problem and I used most of the params (autoreconnect etc..), but didn't try the (test_on_idle, or test_on_connect) , I am going to do them next.
However, I had this hack that got me through this:
I have a cron job called Healthcheck, It wakes up every 10 mins and makes a REST API call to the server. The web / app server picks this up, connects to the db, makes a small change and comes back with a 'yes all quiet on western front' or 'shitshappening'. When the latter, it sends a pager / email to the right people.
It has the side effect of always keeping the db connection pool fresh. So long as this cron is running, I don't have the db connection timeout issues. otherwise, they crop up.
If there are any readers who encountered this issue for accessing remote server: make sure the port is open
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.
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.
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!
I got the communications failure error when using a java.sql.PreparedStatement with a specific statement.
This was running against MySQL 5.6, Tomcat 7.0.29 and JDK 1.7.0_67 on a Windows 7 x64 machine.
The cause turned out to be setting an integer to a string parameter and a string to an integer parameter then trying to perform executeQuery on the prepared statement. After I corrected the order of parameter setting the statement performed correctly.
This had nothing to do with network issues as the wording of the error message suggested.
Source: Stackoverflow.com