com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链接失败 [英] com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:Communications link failure

查看:30
本文介绍了com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链接失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我连接到 MySQL 数据库的程序运行良好.然后,在不更改用于设置连接的任何代码的情况下,我收到此异常:

My program that connects to a MySQL database was working fine. Then, without changing any code used to set up the connection, I get this exception:

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.

发生了什么?

用于获取连接的代码:

private static Connection getDBConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    String username = "user";
    String password = "pass";
    String url = "jdbc:mysql://www.domain.com:3306/dbName?connectTimeout=3000";

    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
}

推荐答案

这是一个包装的异常,并不是很有趣.异常的根本原因实际上告诉了我们一些有关根本原因的信息.请在堆栈跟踪中进一步查看.然后你很可能会遇到SQLException:连接被拒绝SQLException:连接超时.

This is a wrapped exception and not really interesting. It is the root cause of the exception which actually tells us something about the root cause. Please look a bit further in the stacktrace. The chance is big that you'll then face a SQLException: Connection refused or SQLException: Connection timed out.

如果您的情况也是如此,那么所有可能的原因是:

If this is true in your case as well, then all the possible causes are:

  1. JDBC URL 中的 IP 地址或主机名错误.
  2. 本地 DNS 服务器无法识别 JDBC URL 中的主机名.
  3. JDBC URL 中的端口号丢失或错误.
  4. 数据库服务器已关闭.
  5. 数据库服务器不接受 TCP/IP 连接.
  6. Java 和 DB 之间的某些东西正在阻止连接,例如防火墙或代理.

要解决一个或两个,请遵循以下建议:

To solve the one or the either, follow the following advices:

  1. 使用 ping 验证和测试它们.
  2. 刷新 DNS 或改用 JDBC URL 中的 IP 地址.
  3. 根据MySQL DB的my.cnf进行验证.
  4. 开始吧.
  5. 验证是否在没有 --skip-networking 选项的情况下启动了 mysqld.
  6. 禁用防火墙和/或配置防火墙/代理以允许/转发端口.
  1. Verify and test them with ping.
  2. Refresh DNS or use IP address in JDBC URL instead.
  3. Verify it based on my.cnf of MySQL DB.
  4. Start it.
  5. Verify if mysqld is started without the --skip-networking option.
  6. Disable firewall and/or configure firewall/proxy to allow/forward the port.

顺便说一下(与实际问题无关),您不一定需要在每次 getConnection() 调用时加载 JDBC 驱动程序.启动时只需一次就足够了.

By the way (and unrelated to the actual problem), you don't necessarily need to load the JDBC driver on every getConnection() call. Just only once during startup is enough.

这篇关于com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链接失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆