Home > Net >  Java CommunicationsException with MySQL while server running
Java CommunicationsException with MySQL while server running

Time:12-24

My program connects to MySQL by mysql-connector-java-8.0.14 (JDBC Driver). A lot of devices and web-app connects to server for pending data.

Everything clear, but if server worked all night without web-app then auth to server failed.

After reading of logs I found the line [com.mysql.cj.jdbc.exceptions.CommunicationsException], but I have never closed connection to MySQL.

After re-run server, it work fine.

My piece of code:

...

/**
 * Class works with database.
 */
public class DBHelper {

    /**
     * Connection to database.
     */
    private static Connection cn;

    ...

    /**
     * Connect to MySQL, perform database creation script if necessary, and then
     *        connect to database.
     * @param host host MySQL-server for connecting
     * @param port port MySQL-server for connecting
     * @param user user for connecting
     * @param password password for connecting
     * @throws SQLException syntax or connection MySQL exception
     * @throws IOException database import file read failure
     */
    protected static void connectMySqlDb(String host, String port, String user, String password) 
        throws SQLException, IOException {

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            log(ex);
        }

        final String conn = "jdbc:mysql://"   host   ":"   port   "/<db>?user="   user   
                "&password="   password   "&allowMultiQueries=true&serverTimezone=UTC&"   
                "useSSL=false&verifyServerCertificate=false";
        cn = DriverManager.getConnection(conn);

        ...

    }

}

I've tried to catch CommunicationsException and reconnect if it possible. It's ok, but I think it's not so clear.

CodePudding user response:

It looks like MySQL database drops connection after 8 hours. How to prevent it?

You can use 'autoReconnect' parameter with 'true' value in your conn variable.

final String conn = "jdbc:mysql://"   host   ":"   port   "/<db>?user="   user   "&password="   password   "&allowMultiQueries=true&serverTimezone=UTC&"   "useSSL=false&verifyServerCertificate=false&autoReconnect=true";
  • Related