99 lines
2.6 KiB
Java
99 lines
2.6 KiB
Java
package net.saltymc.eaa.util.database;
|
|
|
|
import net.saltymc.eaa.EaaMod;
|
|
|
|
import java.sql.*;
|
|
import com.mysql.cj.jdbc.Driver;
|
|
|
|
public class Postgre {
|
|
|
|
private String url;
|
|
private String user;
|
|
private String password;
|
|
private String db_name;
|
|
|
|
private final String driverName = "com.mysql.cj.jdbc.Driver";
|
|
|
|
|
|
private static Postgre postgre;
|
|
private Connection connection;
|
|
|
|
public Postgre() {
|
|
|
|
this.url = EaaMod.getSettings().getProperty("url");
|
|
this.user = EaaMod.getSettings().getProperty("user");
|
|
this.password = EaaMod.getSettings().getProperty("password");
|
|
this.db_name = EaaMod.getSettings().getProperty("db_name");
|
|
|
|
try {
|
|
//load driver / config driver
|
|
EaaMod.LOGGER.debug("Lade DB Treiber");
|
|
|
|
new Driver();
|
|
|
|
connection = DriverManager.getConnection("jdbc:" + url + db_name , user, password);
|
|
|
|
} catch (SQLException e){
|
|
EaaMod.LOGGER.error(e.getMessage());
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
|
|
|
|
static Postgre getInstance(){
|
|
if (postgre == null)
|
|
postgre = new Postgre();
|
|
|
|
return postgre;
|
|
}
|
|
|
|
static PreparedStatement getStatement(String statement) throws SQLException{
|
|
return getInstance().connection.prepareStatement(statement);
|
|
}
|
|
|
|
/**
|
|
* closes current connection and reload it
|
|
*/
|
|
private void reload(){
|
|
cleanUp();
|
|
|
|
try {
|
|
//load driver / config driver
|
|
EaaMod.LOGGER.debug("Lade DB Treiber");
|
|
Class driver_class = Class.forName(driverName);
|
|
Driver dbdriver = (Driver) driver_class.newInstance();
|
|
DriverManager.registerDriver(dbdriver);
|
|
|
|
try {
|
|
EaaMod.LOGGER.debug("Create connection to Database");
|
|
//Create connection
|
|
connection = DriverManager.getConnection("jdbc:" + url + db_name , user, password);
|
|
} catch (SQLException e) {
|
|
EaaMod.LOGGER.error(e.getMessage());
|
|
}
|
|
} catch (Exception e){
|
|
EaaMod.LOGGER.error(e.getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Inspired by https://www.vogella.com/tutorials/MySQLJava/article.html
|
|
*
|
|
* CleanUp of SQL connection
|
|
*/
|
|
public void cleanUp(){
|
|
EaaMod.LOGGER.debug("Close database connection");
|
|
try {
|
|
|
|
connection.setAutoCommit(true);
|
|
|
|
if (connection != null)
|
|
connection.close();
|
|
|
|
connection = null;
|
|
} catch(SQLException e){
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
}
|