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.setMaximumPoolSize(10); config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"); config.addDataSourceProperty("serverName", hostname); config.addDataSourceProperty("port", port); config.addDataSourceProperty("databaseName", database); config.addDataSourceProperty("user", username); config.addDataSourceProperty("password", 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; } }