A
A
Andrei St2021-02-23 20:42:21
Java
Andrei St, 2021-02-23 20:42:21

How to add AutoRecconetTrue in java?

In my java script, connections to mysql are constantly disconnected because the same application accesses the same database!

ERROR CODE:

Caused by: com.mysql.cj.exceptions.CJCommunicationsException: The last packet successfully received from the server was 6,471,540 milliseconds ago.  The last packet sent successfully to the server was 6,471,540 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.


autoReconnect=trueTell me how to add a function to my java code in this case ?

public static Connection getMySqlConnection(String host, int port, String database, String user, String password) {
        StringBuilder sb = new StringBuilder(host);
        if (port >= 0) sb.append(":").append(port);
        sb.append("/").append(database);
        sb.append("?useSSL=false");
        return getMySqlConnection(sb.toString(), user, password);
    }


public static String getMySqlUrl(String host, int port, String database) {
        StringBuilder sb = new StringBuilder("jdbc:mysql://").append(host);
        if (port >= 0) sb.append(":").append(port);
        sb.append("/").append(database).append("?useSSL=false");
        return sb.toString();
    }


public String getDbUrl() {
        StringBuilder sb = new StringBuilder("jdbc:");
        if (dbUseMySQL()) {
            sb.append("mysql://")
                    .append(dbMySqlUrl())
                    .append(":").append(dbMySqlPort())
                    .append("/").append(dbMySqlDatabase())
                    .append("?useSSL=false");
        } else {
            sb.append("sqlite:")
                    .append(dbFileName());
        }
        return sb.toString();
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-02-23
@xez

Just add url autoReconnect=true to jdbc
It doesn't seem like a good idea to use StringBuilder in your case.
I think it's better like this:

String url = String.format("jdbc:mysql://%s:%d/%s?useSSL=false&autoReconnect=true", 
dbMySqlUrl(), dbMySqlPort(), dbMySqlDatabase());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question