Commons/src/main/java/eu/univento/commons/database/MySQL.java

74 lines
2.0 KiB
Java

package eu.univento.commons.database;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author joethei
* @version 0.1
*/
public class MySQL {
private final HikariDataSource dataSource;
public MySQL(String hostname, String port, String database, String username, String password) {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://" + hostname + ":" + port + "/" + database);
config.setUsername(username);
config.setPassword(password);
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
dataSource = new HikariDataSource(config);
}
public void close() {
try {
dataSource.getConnection().close();
dataSource.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public HikariDataSource getDataSource() {
return dataSource;
}
public Connection getConnection() {
try {
if (dataSource.getConnection() != null)
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public int update(String sql) {
try {
PreparedStatement statement = getConnection().prepareStatement(sql);
return statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
public ResultSet query(String sql) {
PreparedStatement statement;
try {
statement = getConnection().prepareStatement(sql);
return statement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}