当出现:

Cannot connect to database server
Communications link failure
错误时,可以考虑下面的文章:
http://stackoverflow.com/questions/6865538/solving-a-communications-link-failure-with-jdbc-and-mysql

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

java mysql jdbc
share|improve this question
asked Jul 28 '11 at 20:55
Anthony
28115

 
1  
Note the CausedBy at the bottom. The SQL server never accepted the connection. What happens if do (from a command line) telnet localhost 3306? Is the mySQL server running? – Jim Garrison Jul 28 '11 at 20:59
 
Check this post. Might help: stackoverflow.com/questions/15949/… – maclema Jul 28 '11 at 21:07
 
Problem solved, added a bind-address entry to my.cnf. – Anthony Jul 28 '11 at 21:28
 
What address did you put for your bind-address? – prolink007 Oct 11 '11 at 21:45
1  
@Anthony You should put your comment as an answer and accept it ... – Fildor Nov 1 '11 at 17:24

show 1 more comment

4 Answers

activeoldestvotes

up vote14down vote

I have had the same problem in two of my programs. My error was this:

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.

I spend some 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.

point: For the solutions that you need to change the MySQL settings, you can refer to the following not:

  • Linux: /etc/my.cnf

  • Windows: D:\Program Files\mysql\bin\my.ini

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 = number

interactive_timeout = number

connect_timeout = number

  • check Operating System proxy settings

Make sure the Fire wall, or Anti virus soft wares don't block MySQL service.

  • 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 your port, like 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 how 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 created connection and then closed it. Although I closed 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.

Solving a “communications link failure” with jdbc and mysql :Cannot connect to database server Commu相关推荐

  1. 【Mysql】Communications link failure,The last packet sent successfully to the server was 0 millisecond

    项目背景是数据库和项目不在同一台服务器下,在启动时,突然遇到以下错误: Exception in thread "main" com.mysql.jdbc.exceptions.j ...

  2. com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

    com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure 数据库jdbc连接异常,数据库连接异 ...

  3. Communications link failure,The last packet successfully received from the serve

    最近做测试,发现Mysql 过一段时间会无法连接,导致数据库数据不一至,极其郁闷. 使用Connector/J连接MySQL数据库,程序运行较长时间后就会报以下错误: Communications l ...

  4. Connection timed out: connect; Communications link failure

    今天过来启动自己的项目出现如下的问题: Communications link failure The last packet sent successfully to the server was ...

  5. Communications link failure的解决办法

    使用Connector/J连接MySQL数据库,程序运行较长时间后就会报以下错误: Communications link failure,The last packet successfully r ...

  6. MySQL数据库提示:Communications link failure,The last packet succe

    Last modified:2013-10-08 14:16:47      **********************************************       web网站使用M ...

  7. com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure 数据库报错

    -- 查询mysql 数据库链接空闲时间持有最大空闲时间,单位为秒 SHOW VARIABLES WHERE VAriable_name = 'interactive_timeout'; -- 会出现 ...

  8. com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    昨天数据库做了一些改动,早上再打开的项目的时候就出现了这样的问题 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communicat ...

  9. Underlying cause: com.mysql.cj.jdbc.exceptions.CommunicationsException : Communications link failure

    Hive试图schematool -dbType mysql -initSchema时候报错如下: Metastore connection URL:     jdbc:mysql://Desktop ...

最新文章

  1. WPF的Timer控件的使用
  2. java批量执行查询sql语句_详解MyBatis直接执行SQL查询及数据批量插入
  3. boost::weak_from_raw相关的测试程序
  4. 人工智能——图像分析第二期练习
  5. 【转】无刷新验证用户名可用性
  6. YY的GCD(洛谷-P2257)
  7. HibernateDaoSupport类的使用(转)
  8. vba for wps 7.0_两表数据核对,WPS表格真香
  9. VR养狗,养的是寂寞还是潮流?
  10. UI/UE设计师修炼指南-CSDN公开课-专题视频课程
  11. 分水岭算法c语言,分水岭算法的概念及原理
  12. 关于Markdown编辑器
  13. 英语基础太差,到底能不能学好编程?
  14. linux安装beyondcompare
  15. 两个对象值相同(x.equals(y) == true),但却可有不同的hash code,这句话对不对
  16. 工信部:深入推进制造和网络强国建设
  17. 百度竞价排名曝光_百度爱采购的三大优势,及如何发优质商品。
  18. CSDN专属idea插件上线啦~~
  19. 排查OOM流程,直播界面
  20. 女学霸考692分想当“程序媛”,女生到底要不要学计算机?

热门文章

  1. FPGA的UART信息回显
  2. UI设计师如何寻找设计灵感来源?
  3. 文件 组织 服务器 数据库,nc文件服务器 数据库文件
  4. python图灵_python图灵机器人
  5. d3dcompiler_47.dll缺失怎么修复?D3DCompiler_47.dll修复工具下载
  6. 尘埃粒子计数器把控半导体车间安全堡垒
  7. 2011年高考模拟命题作文读我
  8. 如何用C++ 写Python模块扩展(一)
  9. yershop商城系统开发(二)——新浪SAE配置
  10. Linux系统中进程的查看及控制