Advertisement
MrGeekk

MySQL

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