PandaLib/src/main/java/fr/pandacube/util/orm/DBConnection.java

78 lines
1.8 KiB
Java
Raw Normal View History

2019-10-26 23:15:49 +02:00
package fr.pandacube.util.orm;
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;
public class DBConnection {
2017-11-04 19:20:53 +01:00
private Connection conn;
private String url;
private String login;
private String pass;
private long timeOfLastCheck = 0;
public DBConnection(String host, int port, String dbname, String l, String p)
throws ClassNotFoundException, SQLException {
2016-07-08 11:33:22 +02:00
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://" + host + ":" + port + "/" + dbname
+ "?autoReconnect=true"
+ "&useUnicode=true"
+ "&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()) {
2017-11-04 19:20:53 +01:00
close();
connect();
2016-07-08 11:33:22 +02:00
}
}
public boolean isConnected()
{
boolean connected = false;
try (ResultSet rs = conn.createStatement().executeQuery("SELECT 1;"))
{
if (rs == null)
connected = false;
else if (rs.next())
connected = true;
} catch (Exception e) {
connected = false;
}
return connected;
}
public Connection getNativeConnection() throws SQLException {
2017-11-04 19:20:53 +01:00
if (conn.isClosed())
connect();
long now = System.currentTimeMillis();
if (timeOfLastCheck + 5000 > now) {
timeOfLastCheck = now;
if (!conn.isValid(1))
checkConnection();
2017-11-04 19:20:53 +01:00
}
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 e) {}
2016-07-08 11:33:22 +02:00
}
2016-07-08 11:33:22 +02:00
}