79 lines
2.2 KiB
Java
79 lines
2.2 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 String username;
|
|
private final String database;
|
|
private final String password;
|
|
private final String port;
|
|
private final String hostname;
|
|
|
|
private final HikariDataSource dataSource;
|
|
|
|
public MySQL(String hostname, String port, String database, String username, String password) {
|
|
this.username = username;
|
|
this.database = database;
|
|
this.password = password;
|
|
this.port = port;
|
|
this.hostname = hostname;
|
|
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);
|
|
}
|
|
|
|
void close() {
|
|
dataSource.close();
|
|
}
|
|
|
|
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;
|
|
}
|
|
} |