Вопрос-ответ

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

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: сбой канала связи

Я работаю над тем, чтобы моя база данных взаимодействовала с моими программами Java.

Кто-нибудь может дать мне быстрый и грязный пример программы, использующей JDBC?

Я получаю довольно грандиозную ошибку:

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

Содержимое тестового файла:

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?");
}
}
Переведено автоматически
Ответ 1

Итак, у вас есть


com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: сбой канала связи
java.net.ConnectException: отказано в подключении


Я цитирую из этого ответа, который также содержит пошаговое руководство по MySQL + JDBC:


Если вы получаете SQLException: Connection refused или Connection timed out или специфичный для MySQL CommunicationsException:
Communications link failure
, то это означает, что база данных вообще недоступна. Это может быть вызвано одной или несколькими из следующих причин:



  1. IP-адрес или имя хоста в URL JDBC неверны.

  2. Имя хоста в URL JDBC не распознается локальным DNS-сервером.

  3. Номер порта отсутствует или указан неправильно в URL JDBC.

  4. Сервер БД не работает.

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




See also:

Ответ 2

In my case, the solution was to add the expected TLS protocol to the connection string like this:

jdbc:mysql://localhost:3306/database_name?enabledTLSProtocols=TLSv1.2

For testing/development purposes (not recommended for production) you can also try:

jdbc:mysql://localhost:3306/database_name?useSSL=false&allowPublicKeyRetrieval=true
Ответ 3

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");
Ответ 4

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.

java mysql jdbc