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

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.

Related

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.

PhpStorm + MySQL Setup

I have been trying to set up a new MySQL connection in PhpStorm (2016.1) for days now and cannot figure it out.
I am on a Mac OS X 10.11.4 and I have a Home Server (Ubuntu 14.04) and MySQL (5.5). I have a Firewall setup on the Server and have allowed all local connections to pass through (verified by connecting to MySQL on another computer).
I went into PhpStorm and added a new Database, entered the IP address (even tried host name) of remote (Home Server), and all credentials. When I hit "Test Connection" I get an error of
"Connection refused to host: localhost; nested exception is:
java.net.ConnectException: Connection Refused"
I have "googled" about this error and one suggestion is to uncomment the localhost line in your hosts file (it was never commented out). I then though, maybe I need to have MySQL installed on my Mac, so I installed the current MySQL. Still get the same error. I even went under the SSH tab (PhpStorm) under the database setup and tried to set up a SSH Tunnel, still the same error.
Any suggestions?
(Posted on behalf of the OP).
After talking with JetBrains they were able to help me out. For some reason an address within my /etc/hosts file (on my Mac) was messing the connection up. Once I removed it, it connected. Somehow one of the IP addresses was making it loop back to localhost.

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

I was using mysql 5.6.11,it usually turned down and show me this:
2005 - Unknown MySQL server host 'localhost'(11001).
Currently my resolution is to turn off the network,than it return to normal.I had searched a lot,but no answer is revalent to it.So,does anyone knows the reason?
ERROR 2005 (HY000): Unknown MySQL server host 'localhost' (0)
modify list of host names for your system:
C:\Windows\System32\drivers\etc\hosts
Make sure that you have the following entry:
127.0.0.1 localhost
In my case that entry was 0.0.0.0 localhost which caussed all problem
(you may need to change modify permission to modify this file)
This performs DNS resolution of host “localhost” to the IP address 127.0.0.1.
I have passed through that error today and did everything described above but didn't work for me. So I decided to view the core problem and logged onto the MySQL root folder in Windows 7 and did this solution:
Go to folder:
C:\AppServ\MySQL
Right click and Run as Administrator these files:
mysql_servicefix.bat
mysql_serviceinstall.bat
mysql_servicestart.bat
Then close the entire explorer window and reopen it or clear cache then login to phpMyAdmin again.
The case is like :
mysql connects will localhost when network is not up.
mysql cannot connect when network is up.
You can try the following steps to diagnose and resolve the issue (my guess is that some other service is blocking port on which mysql is hosted):
Disconnect the network.
Stop mysql service (if windows, try from services.msc window)
Connect to network.
Try to start the mysql and see if it starts correctly.
Check for system logs anyways to be sure that there is no error in starting mysql service.
If all goes well try connecting.
If fails, try to do a telnet localhost 3306 and see what output it shows.
Try changing the port on which mysql is hosted, default 3306, you can change to some other port which is ununsed.
This should ideally resolve the issue you are facing.
Follow these steps to fix this error
Use \connect root#127.0.0.1 instead of \connect root#localhost
if it doesn't work then go to C:\Windows\System32\drivers\etc\hosts and check the IP address attached to host name.
use that IP, so it will be.
\connect root#the_ip_address_you_found

Remote mySQL connection throws "cannot connect to MySQL 4.1+ using the old insecure authentication" error from XAMPP

I'm running a local copy of WordPress on XAMPP/WinXP for development, but would like to maintain a connection to the remote database. I keep getting "Error establishing database connection" no matter what I try.
On the same PC, I can connect to the remote mySQL DB using any number of mySQL clients, and on the mySQL side, the both the user and the database are set to accept incoming requests from any wildcard domain. I can also easily ping the remote database server from my PC (though I don't know how to do it from WITHIN XAMPP).
Is XAMPP its own little universe that can't reach through to the outside world? Or is there something I'm clearly overlooking that's not letting me connect?
Errors
Warning: mysql_connect() [function.mysql-connect]: Premature end of data (mysqlnd_wireprotocol.c:553) in C:\xampp\htdocs\dbtest.php on line 5
Warning: mysql_connect() [function.mysql-connect]: OK packet 1 bytes shorter than expected in C:\xampp\htdocs\dbtest.php on line 5
Warning: mysql_connect() [function.mysql-connect]: mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication
Edit
Thanks to #Michael for suggesting I just create a simple connection script so I can get better insight into the actual error that's being thrown. This revealed that it had to do with the old_password setting in mySQL. See my Answer below for a full description of how to resolve this issue.
Here's the test script I put inside my xampp\htdocs folder and tested out:
<?php
$mysqli = new mysqli('my.server.address', 'user_name', 'password', 'database_name');
if ($mysqli->connect_error){
die ("Connect error: " . $mysqli->connect_error );
}
I'm not really clear on why this became an issue on my XAMPP installation, since I'm also running PHP 5.3.x on the server's local box and wasn't experiencing those issues there. However, it has to do with my mySQL server running in "old password" encryption mode. Newer versions of PHP won't allow those kinds of connections, so you need to update your mySQL server to use the newer password encryption. Here are the steps, assuming you have control over the mySQL server. If you don't, that falls out of the scope of my knowledge.
locate the configuration file for the mysql server called my.cnf. I found mine at /etc/my.cnf. You can edit it with sudo nano /etc/my.cnf
Look for a line that says old_passwords=1 and change that to old_passwords=0. You have now told the server that the next time it is run, and it is asked to encrypt a password using the PASSWORD() command, it use the new 41-character encryption rather than the 16-character 'old' style encryption
Now you have to restart your mysql server / service. YMMV, but on Fedora that was easily done with sudo service mysqld restart. Check your OS' instructions for restarting the mysql daemon or service
Now we have to actually edit our user table within mysql. So open up an interactive shell to mysql (on the server you can type mysql -uYourRootUsername -pYourRootPassword)
Change to the mysql database. This is the database that holds all the good stuff for server operation and authentication. You must have root access to work with this database. If you get an 'access denied' you're SOL. Sorry. use mysql; will switch to that database
Now we want to update the user that was giving you grief. Ultimately you'll probably want to update all your users, but for now, we're just focusing on the user that threw the error. update user set Password=password('YOUR_PASSWORD') where User='YOUR_USERNAME';
Now you just need to tell mysql to use the new password for authentication when that user attempts to connect. flush privileges;.
You should be good to go!

Tomcat7 MySQL Connection Error

I'm facing a perplexing problem. I've completed a jsf web app that utlizes hibernate and infinispan with Tomcat7 and tomcat-jdbc-pool as the connection pool provider.
It is being deployed to a Linode cluster w/ 2 nodes -- one database server and one production server.
I can run the app on my local environment using the exact same copy of Tomcat7 (I literally tarred the tomcat directory and promoted it to the server to debug this error) -- even when connected to the live database instance. Everything runs fine.
When I attempt to run the application from the production server I get a MySQLIO error:
Caused by: java.net.ConnectException:
Connection refused
Looking further up in the logs i see:
The last packet sent successfully to
the server was 1 milliseconds ago. The
driver has not received any packets
from the server.
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
I can connect from the command line on the prodapp server just fine -- even using tcp:
mysql -h db01 -u user -p --protocol=tcp
But it just won't work running inside the Tomcat container. I've tried all kinds of things but I'm really stumped. It just seems strange that I can connect to the database server using the same copy of Tomcat7 locally but when deployed to production the same copy of tomcat7 can't connect -- even though I can connect from the command line on that production server ... I'm stumped.
Any help is greatly appreciated.
EDIT: Solved my problem after wasting too much good life on it. The answer was I'm stupid. Thanks to everyone who tried to help. I have the app moded w/ a dev and live mode and the connection pool was reading the dev mode this whole time. What really made it confusing is that the sessionfactory was moded to live so it would actually reach the live database and initialize a connection when it started up so i could see it connecting (and running meta data queries in the mysql log), but when it actually went to grab a connection from infinispan it blew up. Oh well -- at least it's working now. Thanks again.
If you're connecting to your MySQL database server from a different box, then you need to explicitly grant permission for that user account to connect from that IP.
You can do this whilst in the command line:
GRANT ALL PRIVILEGES ON *.* TO 'username'#'ip_address'
EDIT: Granting all permissions on all tables generally isn't required, be specific about what permissions you want to grant (http://dev.mysql.com/doc/refman/5.1/en/grant.html)
To see what permissions you currently have:
USE mysql;
SELECT * FROM users;
My apologies if I'm patronising you, just that this is the most common problem that I come across.