Advertisement
Lisenochek

Untitled

Dec 28th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.77 KB | None | 0 0
  1. package ru.lisenochek.mcrust.sql;
  2.  
  3. import com.zaxxer.hikari.HikariConfig;
  4. import com.zaxxer.hikari.HikariDataSource;
  5. import ru.lisenochek.mcrust.Config;
  6. import ru.lisenochek.mcrust.utils.Logger;
  7.  
  8. import java.sql.Connection;
  9. import java.sql.ResultSet;
  10. import java.sql.SQLException;
  11. import java.sql.Statement;
  12.  
  13. public class SQL {
  14.  
  15. private static SQL sql;
  16.  
  17. private HikariDataSource dataSource;
  18.  
  19. private SQL() {
  20. sql = this;
  21. }
  22.  
  23. public static SQL getSQL() {
  24. return sql == null ? new SQL() : sql;
  25. }
  26.  
  27. public void connect() throws ClassNotFoundException {
  28.  
  29. HikariConfig config = new HikariConfig();
  30.  
  31. Class.forName("org.mariadb.jdbc.Driver");
  32. config.setJdbcUrl("jdbc:mariadb://" + Config.SQL_IP.getString() + ":" + Config.SQL_PORT.getString() + "/" + Config.SQL_DATABASENAME.getString());
  33. config.setUsername(Config.SQL_USER.getString());
  34. config.setPassword(Config.SQL_PASSWORD.getString());
  35. config.setLeakDetectionThreshold(30000);
  36. config.addDataSourceProperty("cachePrepStmts", "true");
  37. config.addDataSourceProperty("prepStmtCacheSize", "10");
  38. dataSource = new HikariDataSource(config);
  39. }
  40.  
  41. public void close() {
  42. if (dataSource != null) dataSource.close();
  43. }
  44.  
  45. public void execute(String query) {
  46.  
  47. if (query == null || query.isEmpty()) {
  48. Logger.getLogger("Невозможно выполнить запрос! Он равен null или пуст!").error();
  49. return;
  50. }
  51.  
  52. try (Connection connection = getConnection(); Statement statement = connection.prepareStatement(query)) {
  53. statement.execute(query);
  54. } catch (SQLException e) {
  55. Logger.getLogger("Что-то пошло не так и при запросе появилось исключение:").error();
  56. e.printStackTrace();
  57. }
  58. }
  59.  
  60. public ResultSet executeQuery(String query) {
  61.  
  62. if (query == null || query.isEmpty()) {
  63. Logger.getLogger("Невозможно выполнить запрос! Он равен null или пуст!").error();
  64. return null;
  65. }
  66.  
  67. ResultSet resultSet = null;
  68.  
  69. try (Connection connection = getConnection(); Statement statement = connection.prepareStatement(query)) {
  70. resultSet = statement.executeQuery(query);
  71. } catch (SQLException e) {
  72. Logger.getLogger("Что-то пошло не так и при запросе появилось исключение:").error();
  73. e.printStackTrace();
  74. }
  75.  
  76. return resultSet;
  77. }
  78.  
  79. private Connection getConnection() throws SQLException {
  80. return dataSource.getConnection();
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement