PandaLib/pandalib-db/src/main/java/fr/pandacube/lib/db/DBConnection.java

84 lines
1.9 KiB
Java
Raw Normal View History

package fr.pandacube.lib.db;
2016-07-08 11:33:22 +02:00
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
2016-07-08 11:33:22 +02:00
import java.sql.SQLException;
import fr.pandacube.lib.util.Log;
2020-02-02 16:36:43 +01:00
2016-07-08 11:33:22 +02:00
public class DBConnection {
2020-02-02 16:36:43 +01:00
private static final long CONNECTION_CHECK_TIMEOUT = 30000; // in ms
2017-11-04 19:20:53 +01:00
private Connection conn;
private final String url;
private final String login;
private final String pass;
2017-11-04 19:20:53 +01:00
private long timeOfLastCheck = 0;
public DBConnection(String host, int port, String dbname, String l, String p)
throws SQLException {
url = "jdbc:mysql://" + host + ":" + port + "/" + dbname
+ "?autoReconnect=true"
+ "&useUnicode=true"
+ "&useSSL=false"
+ "&characterEncoding=utf8"
+ "&characterSetResults=utf8"
+ "&character_set_server=utf8mb4"
+ "&character_set_connection=utf8mb4";
2016-07-08 11:33:22 +02:00
login = l;
pass = p;
connect();
2016-07-08 11:33:22 +02:00
}
private void checkConnection() throws SQLException {
if (!isConnected()) {
2020-02-02 16:36:43 +01:00
Log.info("Connection to the database lost. Trying to reconnect...");
2017-11-04 19:20:53 +01:00
close();
connect();
2016-07-08 11:33:22 +02:00
}
}
private boolean isConnected()
{
2020-02-02 16:36:43 +01:00
try {
if (conn.isClosed())
return false;
2020-02-02 16:36:43 +01:00
// avoid checking the connection everytime we want to do a db request
long now = System.currentTimeMillis();
if (timeOfLastCheck + CONNECTION_CHECK_TIMEOUT > now)
return true;
timeOfLastCheck = now;
if (conn.isValid(1))
return true;
try (ResultSet rs = conn.createStatement().executeQuery("SELECT 1;")) {
return rs != null && rs.next();
2020-02-02 16:36:43 +01:00
}
} catch (Exception e) {
2020-02-02 16:36:43 +01:00
return false;
}
}
public Connection getNativeConnection() throws SQLException {
2020-02-02 16:36:43 +01:00
checkConnection();
2016-07-08 11:33:22 +02:00
return conn;
}
private void connect() throws SQLException {
conn = DriverManager.getConnection(url, login, pass);
2017-11-04 19:20:53 +01:00
timeOfLastCheck = System.currentTimeMillis();
}
2016-07-08 11:33:22 +02:00
public void close() {
try {
conn.close();
} catch (Exception ignored) {}
2016-07-08 11:33:22 +02:00
}
2016-07-08 11:33:22 +02:00
}