猿问

com.mysql.jdbc.exceptions.jdbc4.Communications

com.mysql.jdbc.exceptions.jdbc4.Communications

我正在努力让我的数据库与我的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)

测试文件的内容:

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


一只甜甜圈
浏览 6456回答 4
4回答

翻阅古今

当Java出堆时我抓住了这个异常。如果我尝试在RAM中放入许多数据项 - 首先我捕获“&nbsp;通信链接失败”和下一个“&nbsp;OutOfMemoryError&nbsp;”。我记录了它,我减少了内存消耗(删除1/2数据),一切正常。

慕无忌1623718

这是最好的解决方案,&nbsp;Connection&nbsp;con&nbsp;=&nbsp;DriverManager.getConnection( &nbsp;"jdbc:mysql://localhost:3306/DBname",&nbsp;"root",&nbsp;"root"); &nbsp;Connection&nbsp;con&nbsp;=&nbsp;DriverManager.getConnection( &nbsp;"jdbc:mysql://192.100.0.000:3306/DBname",&nbsp;"root",&nbsp;"root");将Localhost替换为您的IP地址

一只斗牛犬

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException如果数据库连接长时间处于空闲状态,则会发生此异常。这个空闲连接返回true,connection.isClosed();但如果我们尝试执行语句,那么它将触发此异常,因此我建议使用数据库池。
随时随地看视频慕课网APP

相关分类

Java
MySQL
我要回答