Skip to content
Advertisement

CommunicationsException: The last packet sent successfully to the server xxx milliseconds ago

I have a question about MySQL/JDBC connections in Java.

I wrote an application that successfully communicates with a database, but the issue that I recently found out was that my DB connection was dropping, and I need the application to have a connection to the DB at all times.

This is a small snipplet of the error I was getting:

com.mysql.cj.jdbc.exceptions.CommunicationsException: The last packet successfully received from the server was 89,225,584 milliseconds ago. The last packet sent successfully to the server was 89,225,584 milliseconds ago. is longer than the server configured value of ‘wait_timeout’. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property ‘autoReconnect=true’ to avoid this problem. at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003)

This is also a snipplet of the constructor for my DBConnections class:

private final String url = "jdbc:mysql://localhost:3306/", database.....;
private Connection connection;
    

public DBConnector(){
        try {
          //  Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url+database, username, password);
        } catch (Exception ex) {
            System.out.println("Error: " + ex);
        }
    }

In the errors section, I noticed it’s telling me to add autoReconnect=true, I wondered; will my connection still stay up for longer if I structured the connection class like this:

connection = DriverManager.getConnection(url+database+"?autoReconnect=true", username, password);

If not, what else could I do to make sure my connection doesn’t drop?

Advertisement

Answer

What I would suggest is to use a connection pool (Apache DBCP or HikariCP – the last one is currently having the best performance out of all solutions on the market) with configuration of testing connection before borrowing it from the pool. Depending on the library there should be an option like setTestOnBorrow(true).

In real applications you should always use connection pool instead of manually handling connections.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement