Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.lisenochek.mcrust.sql;
- import com.zaxxer.hikari.HikariConfig;
- import com.zaxxer.hikari.HikariDataSource;
- import ru.lisenochek.mcrust.Config;
- import ru.lisenochek.mcrust.utils.Logger;
- import java.sql.Connection;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class SQL {
- private static SQL sql;
- private HikariDataSource dataSource;
- private SQL() {
- sql = this;
- }
- public static SQL getSQL() {
- return sql == null ? new SQL() : sql;
- }
- public void connect() throws ClassNotFoundException {
- HikariConfig config = new HikariConfig();
- Class.forName("org.mariadb.jdbc.Driver");
- config.setJdbcUrl("jdbc:mariadb://" + Config.SQL_IP.getString() + ":" + Config.SQL_PORT.getString() + "/" + Config.SQL_DATABASENAME.getString());
- config.setUsername(Config.SQL_USER.getString());
- config.setPassword(Config.SQL_PASSWORD.getString());
- config.setLeakDetectionThreshold(30000);
- config.addDataSourceProperty("cachePrepStmts", "true");
- config.addDataSourceProperty("prepStmtCacheSize", "10");
- dataSource = new HikariDataSource(config);
- }
- public void close() {
- if (dataSource != null) dataSource.close();
- }
- public void execute(String query) {
- if (query == null || query.isEmpty()) {
- Logger.getLogger("Невозможно выполнить запрос! Он равен null или пуст!").error();
- return;
- }
- try (Connection connection = getConnection(); Statement statement = connection.prepareStatement(query)) {
- statement.execute(query);
- } catch (SQLException e) {
- Logger.getLogger("Что-то пошло не так и при запросе появилось исключение:").error();
- e.printStackTrace();
- }
- }
- public ResultSet executeQuery(String query) {
- if (query == null || query.isEmpty()) {
- Logger.getLogger("Невозможно выполнить запрос! Он равен null или пуст!").error();
- return null;
- }
- ResultSet resultSet = null;
- try (Connection connection = getConnection(); Statement statement = connection.prepareStatement(query)) {
- resultSet = statement.executeQuery(query);
- } catch (SQLException e) {
- Logger.getLogger("Что-то пошло не так и при запросе появилось исключение:").error();
- e.printStackTrace();
- }
- return resultSet;
- }
- private Connection getConnection() throws SQLException {
- return dataSource.getConnection();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement