Java com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链接失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2983248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:15:22  来源:igfitidea点击:

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

javamysqljdbc

提问by Josh K

I'm working on getting my database to talk to my Java programs.

我正在努力让我的数据库与我的 Java 程序对话。

Can someone give me a quick and dirty sample program using the JDBC?

有人可以给我一个使用 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?");
    }
}

采纳答案by BalusC

So, you have a

所以,你有一个

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
java.net.ConnectException: Connection refused

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链接失败
java.net.ConnectException:连接被拒绝

I'm quoting from this answerwhich also contains a step-by-step MySQL+JDBC tutorial:

我引用了这个答案,其中还包含一个分步 MySQL+JDBC 教程:

If you get a SQLException: Connection refusedor Connection timed outor 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:

  1. IP address or hostname in JDBC URL is wrong.
  2. Hostname in JDBC URL is not recognized by local DNS server.
  3. Port number is missing or wrong in JDBC URL.
  4. DB server is down.
  5. DB server doesn't accept TCP/IP connections.
  6. DB server has run out of connections.
  7. 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:

  1. Verify and test them with ping.
  2. Refresh DNS or use IP address in JDBC URL instead.
  3. Verify it based on my.cnfof MySQL DB.
  4. Start the DB.
  5. Verify if mysqld is started without the --skip-networking option.
  6. Restart the DB and fix your code accordingly that it closes connections in finally.
  7. Disable firewall and/or configure firewall/proxy to allow/forward the port.

如果您得到一个SQLException: Connection refusedorConnection timed out或 MySQL 特定的CommunicationsException: Communications link failure,则意味着该数据库根本无法访问。这可能有以下一种或多种原因:

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

要解决其中之一,请遵循以下建议:

  1. 验证并测试它们ping
  2. 刷新 DNS 或改用 JDBC URL 中的 IP 地址。
  3. 基于my.cnfMySQL DB 进行验证。
  4. 启动数据库。
  5. 验证 mysqld 是否在没有--skip-networking option.
  6. 重新启动数据库并相应地修复您的代码,以关闭finally.
  7. 禁用防火墙和/或配置防火墙/代理以允许/转发端口。

See also:

也可以看看:

回答by stacker

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.

下载的MySQL-JDBC型-4-二极管驱动器(IG 'MySQL的连接器的Java-5.1.11-bin.jar'从'mysql-connector-java-5.1.11.zip')在Mysql的

You need to inculde the driver jar during compile- and runtime in your classpath.

您需要在类路径中的编译和运行期间包含驱动程序 jar。

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

回答by Karl Walsh

I might be barking up the wrong tree here, but your exception seems to indicate your MySQL server isn't available.

我可能在这里吠错了树,但您的异常似乎表明您的 MySQL 服务器不可用。

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

线程“main”com.mysql.jdbc.exceptions.jdbc4.CommunicationsException 中的异常:通信链接失败最后一个数据包成功发送到服务器是 0 毫秒前。驱动程序没有收到来自服务器的任何数据包。在...

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?

系统将提示您输入与用户名关联的密码。在您提供正确的密码后,mysql 客户端是否连接?

You may have to start MySQL from the Preferences if not. You can also set it to run at startup.

如果没有,您可能必须从首选项启动 MySQL。您还可以将其设置为在启动时运行。

回答by rs2012

I got the same error because I was trying to run my program without starting mysql server.

我遇到了同样的错误,因为我试图在不启动 mysql 服务器的情况下运行我的程序。

After starting the mysql server, everything went right.

启动mysql服务器后,一切正常。

回答by mel3kings

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.

问候。

回答by user1694306

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

当 Java 出堆时,我会捕获此异常。如果我尝试在 RAM 中放入许多数据项 - 首先我会捕获“通信链接失败”,然后是“ OutOfMemoryError”。

I logged it and I decrease memory consumption (delete 1/2 data) and all ok.

我记录了它并减少了内存消耗(删除了 1/2 数据),一切正常。

回答by sureshAngamuthu

In my case, I needed to do a replacement of Localhost to the actual database server IP address

就我而言,我需要将 Localhost 替换为实际的数据库服务器 IP 地址

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

回答by user3427633

I had the same problem, and here's how it was fixed:

我遇到了同样的问题,这是修复方法:

  1. My .jsp was calling attributes that I had not yet defined in the servlet.
  2. I had two column names that I was passing into an object through ResultSet (getString("columnName"))that didn't match the column names in my database.
  1. 我的 .jsp 正在调用我尚未在 servlet 中定义的属性。
  2. 我有两个列名传递给一个对象ResultSet (getString("columnName")),但与我的数据库中的列名不匹配。

I'm not exactly sure which one fixed the problem, but it worked. Also, be sure that you create a new Statementand ResultSetfor each table query.

我不确定哪一个解决了问题,但它有效。此外,请确保为每个表创建一个新的StatementResultSet查询。

回答by Sreedhar GS

Please update your IP address in /etc/mysql/my.cnf file

请在 /etc/mysql/my.cnf 文件中更新您的 IP 地址

bind-address  = 0.0.0.0

Restart mysql deamon and mysql services.

重启mysql deamon 和mysql 服务。

回答by Haimei

My same problem is solved by the following steps:

我的相同问题通过以下步骤解决:

  1. Go to my.cnf

    vi /etc/mysql/my.cnf
    
  2. Modify its bind-address

    "bind-address = 0.0.0.0"
    
  3. Restart MySQL

    sudo /etc/init.d/mysql restart
    
  1. my.cnf

    vi /etc/mysql/my.cnf
    
  2. 修改其绑定地址

    "bind-address = 0.0.0.0"
    
  3. 重启 MySQL

    sudo /etc/init.d/mysql restart