com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
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
orConnection timed out
or a MySQL specificCommunicationsException: 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?
I catch this exception when Java out of heap. If I try to put in RAM many data items - first I catch "Communications link failure" and next "OutOfMemoryError".
I logged it and I decrease memory consumption (delete 1/2 data) and all ok.
In my case, I 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");