Alexousd

DEV' PLUGIN MODERATION #09 - MySQL

May 8th, 2018
573
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.95 KB | None | 0 0
  1. package fr.itsalexousd.moderation.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.     private Connection getConnection() throws SQLException {
  20.         return connectionPool.getConnection();
  21.     }
  22.  
  23.     public void createTables(){
  24.         update("CREATE TABLE IF NOT EXISTS reports (" +
  25.                 "`#` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, " +
  26.                 "pseudo VARCHAR(255), " +
  27.                 "uuid VARCHAR(255), " +
  28.                 "date VARCHAR(255), " +
  29.                 "auteur VARCHAR(255), " +
  30.                 "raison VARCHAR(255))");
  31.     }
  32.  
  33.     public void update(String qry){
  34.         try (Connection c = getConnection();
  35.              PreparedStatement s = c.prepareStatement(qry)) {
  36.             s.executeUpdate();
  37.         } catch(Exception e){
  38.             e.printStackTrace();
  39.         }
  40.     }
  41.  
  42.     public Object query(String qry, Function<ResultSet, Object> consumer){
  43.         try (Connection c = getConnection();
  44.              PreparedStatement s = c.prepareStatement(qry);
  45.              ResultSet rs = s.executeQuery()) {
  46.             return consumer.apply(rs);
  47.         } catch(SQLException e){
  48.             throw new IllegalStateException(e.getMessage());
  49.         }
  50.     }
  51.  
  52.     public void query(String qry, Consumer<ResultSet> consumer){
  53.         try (Connection c = getConnection();
  54.              PreparedStatement s = c.prepareStatement(qry);
  55.              ResultSet rs = s.executeQuery()) {
  56.             consumer.accept(rs);
  57.         } catch(SQLException e){
  58.             throw new IllegalStateException(e.getMessage());
  59.         }
  60.     }
  61. }
Add Comment
Please, Sign In to add comment