Advertisement
Guest User

Untitled

a guest
Dec 11th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. package fr.alwan.hypnosiaplugin.database;
  2.  
  3. import org.apache.commons.dbcp2.BasicDataSource;
  4.  
  5. import java.sql.Connection;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.SQLException;
  9. import java.util.function.Consumer;
  10. import java.util.function.Function;
  11.  
  12. public class MySQL {
  13. private BasicDataSource connectionPool;
  14.  
  15. public MySQL(BasicDataSource connectionPool) {
  16. this.connectionPool = connectionPool;
  17. }
  18.  
  19. public Connection getConnection() throws SQLException {
  20. return connectionPool.getConnection();
  21. }
  22.  
  23. public void createTables() {
  24. update("CREATE TABLE IF NOT EXISTS accounts (" +
  25. "`#` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, " +
  26. "playername VARCHAR(255), " +
  27. "grade VARCHAR(255), " +
  28. "grade_end BIGINT, " +
  29. "coins BIGINT)");
  30. }
  31.  
  32. public void update(String qry) {
  33. try (Connection c = getConnection();
  34. PreparedStatement s = c.prepareStatement(qry)) {
  35. s.executeUpdate();
  36. } catch (Exception e) {
  37. e.printStackTrace();
  38. }
  39. }
  40.  
  41. public Object query(String qry, Function<ResultSet, Object> consumer) {
  42. try (Connection c = getConnection();
  43. PreparedStatement s = c.prepareStatement(qry);
  44. ResultSet rs = s.executeQuery()) {
  45. return consumer.apply(rs);
  46. } catch (SQLException e) {
  47. throw new IllegalStateException(e.getMessage());
  48. }
  49. }
  50.  
  51. public void query(String qry, Consumer<ResultSet> consumer) {
  52. try (Connection c = getConnection();
  53. PreparedStatement s = c.prepareStatement(qry);
  54. ResultSet rs = s.executeQuery()) {
  55. consumer.accept(rs);
  56. } catch (SQLException e) {
  57. throw new IllegalStateException(e.getMessage());
  58. }
  59. }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement