Docker compose configuration for Tomcat+MySql web application [duplicate] - mysql

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

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:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
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:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
Is it safe to use a static java.sql.Connection instance in a multithreaded system?

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

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

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.

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.

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

Add this
useSSL=false&allowPublicKeyRetrieval=true
jdbc:mysql://localhost:3306/cloudapp?useSSL=false&allowPublicKeyRetrieval=true
https://youtu.be/ray3YvnIohM

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.

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.

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.

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 = 0.0.0.0
Restart mysql deamon and mysql services.

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

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

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

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.

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

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.

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

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>

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.

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.

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.

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

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'

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

Related

How to fix this error in docker compose ? CommunicationsException: Communications link failure docker-springboot-example_1 [duplicate]

This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 6 years ago.
I'm trying to connect to the local MySQL server but I keep getting an error.
Here is the code.
public class Connect {
public static void main(String[] args) {
Connection conn = null;
try {
String userName = "myUsername";
String password = "myPassword";
String url = "jdbc:mysql://localhost:3306/myDatabaseName";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Database connection established");
} catch (Exception e) {
System.err.println("Cannot connect to database server");
System.err.println(e.getMessage());
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
System.out.println("Database Connection Terminated");
} catch (Exception e) {}
}
}
}
}
and the errors :
Cannot connect to database server
Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
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:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2333)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2370)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2154)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:792)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.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:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at Connect.main(Connect.java:16)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
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:257)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:294)
... 15 more
I've set the classpath, made sure my.cnf had the skip network option commented out.
java version is 1.2.0_26 (64 bit)
mysql 5.5.14
mysql connector 5.1.17
I made sure that the user had access to my database.
I have had the same problem in two of my programs. My error was this:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
I spent several days to solve this problem. I have tested many approaches that have been mentioned in different web sites, but non of them worked. Finally I changed my code and found out what was the problem. I'll try to tell you about different approaches and sum them up here.
While I was seeking the internet to find the solution for this error, I figured out that there are many solutions that worked for at least one person, but others say that it doesn't work for them! why there are many approaches to this error?
It seems this error can occur generally when there is a problem in connecting to the server. Maybe the problem is because of the wrong query string or too many connections to the database.
So I suggest you to try all the solutions one by one and don't give up!
Here are the solutions that I found on the internet and for each of them, there is at least on person who his problem has been solved with that solution.
Tip: For the solutions that you need to change the MySQL settings, you can refer to the following files:
Linux: /etc/mysql/my.cnf or /etc/my.cnf (depending on the Linux distribution and MySQL package used)
Windows: C:\**ProgramData**\MySQL\MySQL Server 5.6\my.ini (Notice it's ProgramData, not Program Files)
Here are the solutions:
changing bind-address attribute:
Uncomment bind-address attribute or change it to one of the following IPs:
bind-address="127.0.0.1"
or
bind-address="0.0.0.0"
commenting out "skip-networking"
If there is a skip-networking line in your MySQL config file, make it comment by adding # sign at the beginning of that line.
change "wait_timeout" and "interactive_timeout"
Add these lines to the MySQL config file:
[wait_timeout][1] = *number*
interactive_timeout = *number*
connect_timeout = *number*
Make sure Java isn't translating 'localhost' to [:::1] instead of [127.0.0.1]
Since MySQL recognizes 127.0.0.1 (IPv4) but not :::1 (IPv6)
This could be avoided by using one of two approaches:
In the connection string use 127.0.0.1 instead of localhost to avoid localhost being translated to :::1
Run java with the option -Djava.net.preferIPv4Stack=true to force java to use IPv4 instead of IPv6. On Linux, this could also be achieved by running (or placing it inside /etc/profile:
export _JAVA_OPTIONS="-Djava.net.preferIPv4Stack=true"
check Operating System proxy settings, firewalls and anti-virus programs
Make sure the Firewall, or Anti-virus software isn't blocking MySQL service.
Stop iptables temporarily on linux. If iptables are misconfigured they may allow tcp packets to be sent to mysql port, but block tcp packets from coming back on the same connection.
# Redhat enterprise and CentOS
systemctl stop iptables.service
# Other linux distros
service iptables stop
Stop anti-virus software on Windows.
change connection string
Check your query string. your connection string should be some thing like this:
dbName = "my_database";
dbUserName = "root";
dbPassword = "";
String connectionString = "jdbc:mysql://localhost/" + dbName + "?user=" + dbUserName + "&password=" + dbPassword + "&useUnicode=true&characterEncoding=UTF-8";
Make sure you don't have spaces in your string. All the connection string should be continues without any space characters.
Try to replace "localhost" with the loopback address 127.0.0.1.
Also try to add port number to your connection string, like:
String connectionString = "jdbc:mysql://localhost:3306/my_database?user=root&password=Pass&useUnicode=true&characterEncoding=UTF-8";
Usually default port for MySQL is 3306.
Don't forget to change username and password to the username and password of your MySQL server.
update your JDK driver library file
test different JDK and JREs (like JDK 6 and 7)
don't change max_allowed_packet
"max_allowed_packet" is a variable in MySQL config file that indicates the maximum packet size, not the maximum number of packets. So it will not help to solve this error.
change tomcat security
change TOMCAT6_SECURITY=yes to TOMCAT6_SECURITY=no
use validationQuery property
use validationQuery="select now()" to make sure each query has responses
AutoReconnect
Add this code to your connection string:
&autoReconnect=true&failOverReadOnly=false&maxReconnects=10
Although non of these solutions worked for me, I suggest you to try them. Because there are some people who solved their problem with following these steps.
But what solved my problem?
My problem was that I had many SELECTs on database. Each time I was creating a connection and then closing it. Although I was closing the connection every time, but the system faced with many connections and gave me that error. What I did was that I defined my connection variable as a public (or private) variable for whole class and initialized it in the constructor. Then every time I just used that connection. It solved my problem and also increased my speed dramatically.
#Conclusion#
There is no simple and unique way to solve this problem. I suggest you to think about your own situation and choose above solutions. If you take this error at the beginning of the program and you are not able to connect to the database at all, you might have problem in your connection string. But If you take this error after several successful interaction to the database, the problem might be with number of connections and you may think about changing "wait_timeout" and other MySQL settings or rewrite your code how that reduce number of connections.
If you are using MAMP PRO, the easy fix, which I really wish I had realized before I started searching the internet for days trying to figure this out. Its really this simple...
You just have to click "Allow Network Access to MySQL" from the MAMP MySQL tab.
Really, thats it.
Oh, and you MIGHT have to still change your bind address to either 0.0.0.0 or 127.0.0.1 like outlined in the posts above, but clicking that box alone will probably solve your problems if you are a MAMP user.
Setting the bind-address to the server's network IP instead of the localhost default, and setting privileges on my user worked for me.
my.cnf:
bind-address = 192.168.123.456
MySql Console:
GRANT ALL PRIVILEGES ON dbname.* to username#'%' IDENTIFIED BY 'password';
In my case,
Change the remote machine mysql configuration at /etc/mysql/my.cnf: change
bind-address = 127.0.0.1
to
#bind-address = 127.0.0.1
On the remote machine, change mysql user permissions with
GRANT ALL PRIVILEGES ON *.* TO 'user'#'%' IDENTIFIED BY 'password';
IMPORTANT: restart mysql on the remote machine: sudo /etc/init.d/mysql restart
I've just faced the same problem.
It happened because the MySQL Daemon was binded to the IP of the machine, which is required to make connection with an user that has permission to connect #your_machine.
In this case, the user should have permission to connect USER_NAME#MACHINE_NAME_OR_IP
I wanted remote access to my machine so I changed in my.cnf from
bind-address = MY_IP_ADDRESS
To
bind-address = 0.0.0.0
Which will allow an user from localhost AND even outside (in my case) to connect to the instance.
Both below permissions will work if you bind the MySQL to 0.0.0.0:
USER_NAME#MACHINE_NAME_OR_IP
USER_NAME#localhost
In my case (I am a noob), I was testing Servlet that make database connection with MySQL and one of the Exception is the one mentioned above.
It made my head swing for some seconds but I came to realize that it was because I have not started my MySQL server in localhost.
After starting the server, the problem was fixed.
So, check whether MySQL server is running properly.
In case you are having problem with a set of Docker containers, then make sure that you do not only EXPOSE the port 3306, but as well map the port from outside the container -p 3306:3306. For docker-compose.yml:
version: '2'
services:
mdb:
image: mariadb:10.1
ports:
- "3306:3306"
…
In my case it was an idle timeout, that caused the connection to be dropped on the server. The connection was kept open, but not used for a long period of time. Then a client restart works, while I believe a reconnect will work as well.
A not bad solution is to have a daemon/service to ping the connection from time to time.
As the detailed answer above says, this error can be caused by many things.
I had this problem too. My setup was Mac OSX 10.8, using a Vagrant managed VirtualBox VM of Ubuntu 12.04, with MySQL 5.5.34.
I had correctly setup port forwarding in the Vagrant config file. I could telnet to the MySQL instance both from my Mac and from within the VM. So I knew the MySQL daemon was running and reachable. But when I tried to connect over JDBC, I got the "Communications link failure" error.
In my case, the problem was solved by editing the /etc/mysql/my.cnf file. Specifically, I commented out the "#bind-address=127.0.0.1" line.
The resolution provided by Soheil was successful in my case.
To clarify, the only change I needed to make was with MySQL's server configuration;
bind-address = **INSERT-IP-HERE**
I am using an external MySQL server for my application. It is a basic Debian 7.5 installation with MySQL Server 5.5 - default configuration.
IMPORTANT:
Always backup the original of any configuration files you may modify. Always take care when elevated as super user.
File
/etc/mysql/my.cnf
Line
bind-address = 192.168.0.103 #127.0.0.1
Restart your MySQL Server service:
/usr/sbin/service mysql restart
As you can see, I simply provided the network IP of the server and commented out the default entry. Please note that simply copy and paste my solution will not work for you, unless by some miracle our hosts share the same IP.
Thanks # Soheil
I know this is an old thread but I have tried numerous things and fixed my issue using the following means..
I'm developing a cross platform app on Windows but to be used on Linux and Windows servers.
A MySQL database called "jtm" installed on both systems. For some reason, in my code I had the database name as "JTM". On Windows it worked fine, in fact on several Windows systems it flew along.
On Ubuntu I got the error above time and time again. I tested it out with the correct case in the code "jtm" and it works a treat.
Linux is obviously a lot less forgiving about case sensitivity (rightly so), whereas Windows makes allowances.
I feel a bit daft now but check everything. The error message is not the best but it does seem fixable if you persevere and get things right.
I just restarted MySQL (following a tip from here: https://stackoverflow.com/a/14238800) and it solved the issue.
I had the same issue on MacOS (10.10.2) and MySql (5.6.21) installed via homebrew.
The confusing thing was that one of my apps connected to the database fine and the other was not.
After trying many things on the app that threw the exception com.mysql.jdbc.CommunicationsException as suggested by the accepted answer of this question to no avail, I was surprised that restarting MySQL worked.
The cause of my issue might have been the following as suggested in the answer in the aforementioned link:
Are you using connection pool ? If yes, then try to restart the
server. Probably few of the connections in your connection pool are in closed state.
It happens (in my case) when there is not enough memory for MySQL. A restart fixes it, but if that's the case consider a nachine with more memory, or limit the memory taken by jvms
Go to Windows services in the control panel and start the MySQL service. For me it worked. When I was doing a Java EE project I got this error" Communication link failure". I restarted my system and then it worked.
After that I again got the same error even after restarting my system. Then I tried to open the MySQL command line console and login with root, even then it gave me an error.
Finally when I started the MySQL service from Windows services, it worked.
Had the same.
Removing port helped in my case, so I left it as jdbc:mysql://localhost/
For me the solution was to change in the conf file of mysql server the parameter bind-address="127.0.0.1" or bind-address="x.x.x.x" to bind-address="0.0.0.0".
Thanks.
If you are using hibernate, this error can be caused for keeping open a Session object more time than wait_timeout
I've documented a case in here for those who are interested.
I found the solution
since MySQL need the Localhost in-order to work.
go to /etc/network/interfaces file and make sure you have the localhost configuration set there:
auto lo
iface lo inet loopback
NOW RESTART the Networking subsystem and the MySQL Services:
sudo /etc/init.d/networking restart
sudo /etc/init.d/mysql restart
Try it now
It is majorly because of weak connection between mysql client and remote mysql server.
In my case it is because of flaky VPN connection.
In phpstorm + vagrant autoReconnect driver option helped.
I was experiencing similar problem and the solution for my case was
changing bind-address = 0.0.0.0 from 127.0.0.1
changing url's localhost to localhost:3306
the thing i felt is we should never give up, i tried every options from this post and from other forums as well...happy it works #saurab
I faced this problem also.
As Soheil suggested,
I went to php.ini file at the path C:\windows\php.ini , then I revised port number in this file.
it is on the line mysqli.default_port =..........
So I changed it in my java app as it's in the php.ini file,now it works fine with me.
For Windows :-
Goto start menu write , "MySqlserver Instance Configuration Wizard" and reconfigure your mysql server instance.
Hope it will solve your problem.
After years having the same issue and no permanent solution this is whats solved it for the past 3 weeks (which is a record in terms of error free operation)
set global wait_timeout=3600;
set global interactive_timeout=230400;
Don't forget to make this permanent if it works for you.
If you are using local emulator, you have to use IP address 10.0.2.2 instead of localhost to access to your local MySQL server.

How to fix "CommunicationsException: Communications link failure"? [duplicate]

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?");
}
}
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:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
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:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
Is it safe to use a static java.sql.Connection instance in a multithreaded system?
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
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");
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.
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.
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'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);
Add this
useSSL=false&allowPublicKeyRetrieval=true
jdbc:mysql://localhost:3306/cloudapp?useSSL=false&allowPublicKeyRetrieval=true
https://youtu.be/ray3YvnIohM
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.
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.
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.
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 = 0.0.0.0
Restart mysql deamon and mysql services.
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" );
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
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
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.
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
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.
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
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>
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.
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.
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.
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();
}
}
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'
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 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
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.

Cannot connect to MySQL image: Could not create connection to database server [duplicate]

This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 6 years ago.
I'm trying to connect to the local MySQL server but I keep getting an error.
Here is the code.
public class Connect {
public static void main(String[] args) {
Connection conn = null;
try {
String userName = "myUsername";
String password = "myPassword";
String url = "jdbc:mysql://localhost:3306/myDatabaseName";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Database connection established");
} catch (Exception e) {
System.err.println("Cannot connect to database server");
System.err.println(e.getMessage());
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
System.out.println("Database Connection Terminated");
} catch (Exception e) {}
}
}
}
}
and the errors :
Cannot connect to database server
Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
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:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2333)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2370)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2154)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:792)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.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:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at Connect.main(Connect.java:16)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
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:257)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:294)
... 15 more
I've set the classpath, made sure my.cnf had the skip network option commented out.
java version is 1.2.0_26 (64 bit)
mysql 5.5.14
mysql connector 5.1.17
I made sure that the user had access to my database.
I have had the same problem in two of my programs. My error was this:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
I spent several days to solve this problem. I have tested many approaches that have been mentioned in different web sites, but non of them worked. Finally I changed my code and found out what was the problem. I'll try to tell you about different approaches and sum them up here.
While I was seeking the internet to find the solution for this error, I figured out that there are many solutions that worked for at least one person, but others say that it doesn't work for them! why there are many approaches to this error?
It seems this error can occur generally when there is a problem in connecting to the server. Maybe the problem is because of the wrong query string or too many connections to the database.
So I suggest you to try all the solutions one by one and don't give up!
Here are the solutions that I found on the internet and for each of them, there is at least on person who his problem has been solved with that solution.
Tip: For the solutions that you need to change the MySQL settings, you can refer to the following files:
Linux: /etc/mysql/my.cnf or /etc/my.cnf (depending on the Linux distribution and MySQL package used)
Windows: C:\**ProgramData**\MySQL\MySQL Server 5.6\my.ini (Notice it's ProgramData, not Program Files)
Here are the solutions:
changing bind-address attribute:
Uncomment bind-address attribute or change it to one of the following IPs:
bind-address="127.0.0.1"
or
bind-address="0.0.0.0"
commenting out "skip-networking"
If there is a skip-networking line in your MySQL config file, make it comment by adding # sign at the beginning of that line.
change "wait_timeout" and "interactive_timeout"
Add these lines to the MySQL config file:
[wait_timeout][1] = *number*
interactive_timeout = *number*
connect_timeout = *number*
Make sure Java isn't translating 'localhost' to [:::1] instead of [127.0.0.1]
Since MySQL recognizes 127.0.0.1 (IPv4) but not :::1 (IPv6)
This could be avoided by using one of two approaches:
In the connection string use 127.0.0.1 instead of localhost to avoid localhost being translated to :::1
Run java with the option -Djava.net.preferIPv4Stack=true to force java to use IPv4 instead of IPv6. On Linux, this could also be achieved by running (or placing it inside /etc/profile:
export _JAVA_OPTIONS="-Djava.net.preferIPv4Stack=true"
check Operating System proxy settings, firewalls and anti-virus programs
Make sure the Firewall, or Anti-virus software isn't blocking MySQL service.
Stop iptables temporarily on linux. If iptables are misconfigured they may allow tcp packets to be sent to mysql port, but block tcp packets from coming back on the same connection.
# Redhat enterprise and CentOS
systemctl stop iptables.service
# Other linux distros
service iptables stop
Stop anti-virus software on Windows.
change connection string
Check your query string. your connection string should be some thing like this:
dbName = "my_database";
dbUserName = "root";
dbPassword = "";
String connectionString = "jdbc:mysql://localhost/" + dbName + "?user=" + dbUserName + "&password=" + dbPassword + "&useUnicode=true&characterEncoding=UTF-8";
Make sure you don't have spaces in your string. All the connection string should be continues without any space characters.
Try to replace "localhost" with the loopback address 127.0.0.1.
Also try to add port number to your connection string, like:
String connectionString = "jdbc:mysql://localhost:3306/my_database?user=root&password=Pass&useUnicode=true&characterEncoding=UTF-8";
Usually default port for MySQL is 3306.
Don't forget to change username and password to the username and password of your MySQL server.
update your JDK driver library file
test different JDK and JREs (like JDK 6 and 7)
don't change max_allowed_packet
"max_allowed_packet" is a variable in MySQL config file that indicates the maximum packet size, not the maximum number of packets. So it will not help to solve this error.
change tomcat security
change TOMCAT6_SECURITY=yes to TOMCAT6_SECURITY=no
use validationQuery property
use validationQuery="select now()" to make sure each query has responses
AutoReconnect
Add this code to your connection string:
&autoReconnect=true&failOverReadOnly=false&maxReconnects=10
Although non of these solutions worked for me, I suggest you to try them. Because there are some people who solved their problem with following these steps.
But what solved my problem?
My problem was that I had many SELECTs on database. Each time I was creating a connection and then closing it. Although I was closing the connection every time, but the system faced with many connections and gave me that error. What I did was that I defined my connection variable as a public (or private) variable for whole class and initialized it in the constructor. Then every time I just used that connection. It solved my problem and also increased my speed dramatically.
#Conclusion#
There is no simple and unique way to solve this problem. I suggest you to think about your own situation and choose above solutions. If you take this error at the beginning of the program and you are not able to connect to the database at all, you might have problem in your connection string. But If you take this error after several successful interaction to the database, the problem might be with number of connections and you may think about changing "wait_timeout" and other MySQL settings or rewrite your code how that reduce number of connections.
If you are using MAMP PRO, the easy fix, which I really wish I had realized before I started searching the internet for days trying to figure this out. Its really this simple...
You just have to click "Allow Network Access to MySQL" from the MAMP MySQL tab.
Really, thats it.
Oh, and you MIGHT have to still change your bind address to either 0.0.0.0 or 127.0.0.1 like outlined in the posts above, but clicking that box alone will probably solve your problems if you are a MAMP user.
Setting the bind-address to the server's network IP instead of the localhost default, and setting privileges on my user worked for me.
my.cnf:
bind-address = 192.168.123.456
MySql Console:
GRANT ALL PRIVILEGES ON dbname.* to username#'%' IDENTIFIED BY 'password';
In my case,
Change the remote machine mysql configuration at /etc/mysql/my.cnf: change
bind-address = 127.0.0.1
to
#bind-address = 127.0.0.1
On the remote machine, change mysql user permissions with
GRANT ALL PRIVILEGES ON *.* TO 'user'#'%' IDENTIFIED BY 'password';
IMPORTANT: restart mysql on the remote machine: sudo /etc/init.d/mysql restart
I've just faced the same problem.
It happened because the MySQL Daemon was binded to the IP of the machine, which is required to make connection with an user that has permission to connect #your_machine.
In this case, the user should have permission to connect USER_NAME#MACHINE_NAME_OR_IP
I wanted remote access to my machine so I changed in my.cnf from
bind-address = MY_IP_ADDRESS
To
bind-address = 0.0.0.0
Which will allow an user from localhost AND even outside (in my case) to connect to the instance.
Both below permissions will work if you bind the MySQL to 0.0.0.0:
USER_NAME#MACHINE_NAME_OR_IP
USER_NAME#localhost
In my case (I am a noob), I was testing Servlet that make database connection with MySQL and one of the Exception is the one mentioned above.
It made my head swing for some seconds but I came to realize that it was because I have not started my MySQL server in localhost.
After starting the server, the problem was fixed.
So, check whether MySQL server is running properly.
In case you are having problem with a set of Docker containers, then make sure that you do not only EXPOSE the port 3306, but as well map the port from outside the container -p 3306:3306. For docker-compose.yml:
version: '2'
services:
mdb:
image: mariadb:10.1
ports:
- "3306:3306"
…
In my case it was an idle timeout, that caused the connection to be dropped on the server. The connection was kept open, but not used for a long period of time. Then a client restart works, while I believe a reconnect will work as well.
A not bad solution is to have a daemon/service to ping the connection from time to time.
As the detailed answer above says, this error can be caused by many things.
I had this problem too. My setup was Mac OSX 10.8, using a Vagrant managed VirtualBox VM of Ubuntu 12.04, with MySQL 5.5.34.
I had correctly setup port forwarding in the Vagrant config file. I could telnet to the MySQL instance both from my Mac and from within the VM. So I knew the MySQL daemon was running and reachable. But when I tried to connect over JDBC, I got the "Communications link failure" error.
In my case, the problem was solved by editing the /etc/mysql/my.cnf file. Specifically, I commented out the "#bind-address=127.0.0.1" line.
The resolution provided by Soheil was successful in my case.
To clarify, the only change I needed to make was with MySQL's server configuration;
bind-address = **INSERT-IP-HERE**
I am using an external MySQL server for my application. It is a basic Debian 7.5 installation with MySQL Server 5.5 - default configuration.
IMPORTANT:
Always backup the original of any configuration files you may modify. Always take care when elevated as super user.
File
/etc/mysql/my.cnf
Line
bind-address = 192.168.0.103 #127.0.0.1
Restart your MySQL Server service:
/usr/sbin/service mysql restart
As you can see, I simply provided the network IP of the server and commented out the default entry. Please note that simply copy and paste my solution will not work for you, unless by some miracle our hosts share the same IP.
Thanks # Soheil
I know this is an old thread but I have tried numerous things and fixed my issue using the following means..
I'm developing a cross platform app on Windows but to be used on Linux and Windows servers.
A MySQL database called "jtm" installed on both systems. For some reason, in my code I had the database name as "JTM". On Windows it worked fine, in fact on several Windows systems it flew along.
On Ubuntu I got the error above time and time again. I tested it out with the correct case in the code "jtm" and it works a treat.
Linux is obviously a lot less forgiving about case sensitivity (rightly so), whereas Windows makes allowances.
I feel a bit daft now but check everything. The error message is not the best but it does seem fixable if you persevere and get things right.
I just restarted MySQL (following a tip from here: https://stackoverflow.com/a/14238800) and it solved the issue.
I had the same issue on MacOS (10.10.2) and MySql (5.6.21) installed via homebrew.
The confusing thing was that one of my apps connected to the database fine and the other was not.
After trying many things on the app that threw the exception com.mysql.jdbc.CommunicationsException as suggested by the accepted answer of this question to no avail, I was surprised that restarting MySQL worked.
The cause of my issue might have been the following as suggested in the answer in the aforementioned link:
Are you using connection pool ? If yes, then try to restart the
server. Probably few of the connections in your connection pool are in closed state.
It happens (in my case) when there is not enough memory for MySQL. A restart fixes it, but if that's the case consider a nachine with more memory, or limit the memory taken by jvms
Go to Windows services in the control panel and start the MySQL service. For me it worked. When I was doing a Java EE project I got this error" Communication link failure". I restarted my system and then it worked.
After that I again got the same error even after restarting my system. Then I tried to open the MySQL command line console and login with root, even then it gave me an error.
Finally when I started the MySQL service from Windows services, it worked.
Had the same.
Removing port helped in my case, so I left it as jdbc:mysql://localhost/
For me the solution was to change in the conf file of mysql server the parameter bind-address="127.0.0.1" or bind-address="x.x.x.x" to bind-address="0.0.0.0".
Thanks.
If you are using hibernate, this error can be caused for keeping open a Session object more time than wait_timeout
I've documented a case in here for those who are interested.
I found the solution
since MySQL need the Localhost in-order to work.
go to /etc/network/interfaces file and make sure you have the localhost configuration set there:
auto lo
iface lo inet loopback
NOW RESTART the Networking subsystem and the MySQL Services:
sudo /etc/init.d/networking restart
sudo /etc/init.d/mysql restart
Try it now
It is majorly because of weak connection between mysql client and remote mysql server.
In my case it is because of flaky VPN connection.
In phpstorm + vagrant autoReconnect driver option helped.
I was experiencing similar problem and the solution for my case was
changing bind-address = 0.0.0.0 from 127.0.0.1
changing url's localhost to localhost:3306
the thing i felt is we should never give up, i tried every options from this post and from other forums as well...happy it works #saurab
I faced this problem also.
As Soheil suggested,
I went to php.ini file at the path C:\windows\php.ini , then I revised port number in this file.
it is on the line mysqli.default_port =..........
So I changed it in my java app as it's in the php.ini file,now it works fine with me.
For Windows :-
Goto start menu write , "MySqlserver Instance Configuration Wizard" and reconfigure your mysql server instance.
Hope it will solve your problem.
After years having the same issue and no permanent solution this is whats solved it for the past 3 weeks (which is a record in terms of error free operation)
set global wait_timeout=3600;
set global interactive_timeout=230400;
Don't forget to make this permanent if it works for you.
If you are using local emulator, you have to use IP address 10.0.2.2 instead of localhost to access to your local MySQL server.

docker-compose + spring-boot + mysql = CommunicationsException: Communications link failure [duplicate]

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?");
}
}
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:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
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:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
Is it safe to use a static java.sql.Connection instance in a multithreaded system?
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
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");
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.
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.
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'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);
Add this
useSSL=false&allowPublicKeyRetrieval=true
jdbc:mysql://localhost:3306/cloudapp?useSSL=false&allowPublicKeyRetrieval=true
https://youtu.be/ray3YvnIohM
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.
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.
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.
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 = 0.0.0.0
Restart mysql deamon and mysql services.
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" );
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
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
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.
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
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.
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
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>
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.
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.
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.
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();
}
}
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'
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 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
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.

Can't access mysql database (running on AWS instance) from my java application

I have a xampp server running on a AWS-EC2 Ubuntu instance, and I have a database there that is called "androiddb". I can access the database by writing in a navigator http://public_ip/phpmyadmin and entering with "root" user and no password.
In another side I have a Java application that needs to connect with that database, and I have the following line in my code to do it:
con = DriverManager.getConnection("jdbc:mysql://public_ip/androiddb",
"root", "");
When I run my application, I get the following error:
Error: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: java.net.ConnectException: Connection refused
STACKTRACE:
java.net.SocketException: java.net.ConnectException: Connection refused
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:284)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2569)
at com.mysql.jdbc.Connection.<init>(Connection.java:1485)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at Presentacion.Presentacion$2.mouseClicked(Presentacion.java:125)
at java.awt.Component.processMouseEvent(Component.java:6519)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6281)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4872)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4501)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:747)
at java.awt.EventQueue.access$300(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:706)
at java.awt.EventQueue$3.run(EventQueue.java:704)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:720)
at java.awt.EventQueue$4.run(EventQueue.java:718)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:717)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
** END NESTED EXCEPTION **
Last packet sent to the server was 19 ms ago.
Also I looked for the port where mysql was running and I used the code:
SHOW VARIABLES
WHERE Variable_name IN (
'hostname',
'port')
I write this piece of code in phpmyadmin in the SQL section, and I get the following output:
Variable_name Value
hostname ip-172-31-23-224
port 0
I don't know what does port 0 mean, it should be 3306 (default mysql port)...
Anyways, I don't know if I'm doing something wrong with the xampp configuration or if it's problem of AWS or anything else.
Could someone help me with this? Thank you very much.
You should ensure your security groups for AWS are open on the 3306 port (or whatever you configure) so they can access the database.
You could trouble shoot by trying to SSH into the machine, can you connect locally? If yes, then look at your security groups and open the port. If you can't connect locally than the database is down and you need to diagnose and configure the DB correctly.
But a connection refused is more than likely a port not being open in the security group.
Just to add what solved his issue:
He checked his security groups and opened the correct ports
Checked locally to see that mySQL wasn't listening on any port
netstat -tlnp to check to see SQL running locally
Checked the my.ini file to see that mysql was configured to listen on a port
Found it wasn't and reconfigured it to listen
It may help some working with phpMyAdmin and AWS and Amazon's relational database service (RDS) to know that phpMyAdmin will not work unless the RDS endpoint is edited into the "localhost" or "127.0.0.1" location in the config.inc.php file. (It is a necessary but not sufficient fix -- you may need to do other things...)
Generalizing a bit, if you are using foo and it has a config file, and you are looking to connect to a database instantiated under RDS, you'll need that endpoint as host entry.