2016-07-15 02:05:22 +02:00
|
|
|
package fr.pandacube.java.util.db.sql_tools;
|
2016-07-08 11:33:22 +02:00
|
|
|
|
|
|
|
import java.sql.Connection;
|
|
|
|
import java.sql.DriverManager;
|
|
|
|
import java.sql.SQLException;
|
|
|
|
import java.sql.Statement;
|
|
|
|
|
|
|
|
public class DBConnection {
|
|
|
|
Connection conn;
|
|
|
|
String url;
|
|
|
|
String login;
|
|
|
|
String pass;
|
2016-07-14 14:22:23 +02:00
|
|
|
|
|
|
|
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");
|
2016-07-14 14:22:23 +02:00
|
|
|
url = "jdbc:mysql://" + host + ":" + port + "/" + dbname;
|
2016-07-08 11:33:22 +02:00
|
|
|
login = l;
|
|
|
|
pass = p;
|
2016-07-12 19:26:49 +02:00
|
|
|
connect();
|
2016-07-08 11:33:22 +02:00
|
|
|
}
|
2016-07-14 14:22:23 +02:00
|
|
|
|
|
|
|
public void reconnectIfNecessary() throws SQLException {
|
|
|
|
try {
|
2016-07-08 11:33:22 +02:00
|
|
|
Statement stmt = conn.createStatement();
|
|
|
|
stmt.close();
|
2016-07-14 14:22:23 +02:00
|
|
|
} catch (SQLException e) {
|
|
|
|
try {
|
|
|
|
close();
|
|
|
|
} catch (Exception ex) {}
|
2016-07-12 19:26:49 +02:00
|
|
|
connect();
|
2016-07-08 11:33:22 +02:00
|
|
|
}
|
|
|
|
}
|
2016-07-14 14:22:23 +02:00
|
|
|
|
|
|
|
public Connection getNativeConnection() throws SQLException {
|
|
|
|
if (!conn.isValid(1)) reconnectIfNecessary();
|
2016-07-08 11:33:22 +02:00
|
|
|
return conn;
|
|
|
|
}
|
2016-07-14 14:22:23 +02:00
|
|
|
|
2016-07-12 19:26:49 +02:00
|
|
|
private void connect() throws SQLException {
|
|
|
|
conn = DriverManager.getConnection(url, login, pass);
|
|
|
|
}
|
2016-07-14 14:22:23 +02:00
|
|
|
|
2016-07-08 11:33:22 +02:00
|
|
|
public void close() {
|
|
|
|
try {
|
|
|
|
conn.close();
|
2016-07-14 14:22:23 +02:00
|
|
|
} catch (Exception e) {}
|
|
|
|
|
2016-07-08 11:33:22 +02:00
|
|
|
}
|
2016-07-14 14:22:23 +02:00
|
|
|
|
2016-07-08 11:33:22 +02:00
|
|
|
}
|