· 5 years ago · May 08, 2020, 08:56 PM
1package fr.azerothh.hub.database;
2
3import org.apache.commons.dbcp2.BasicDataSource;
4import org.bukkit.Bukkit;
5
6import java.sql.Connection;
7import java.sql.PreparedStatement;
8import java.sql.ResultSet;
9import java.sql.SQLException;
10import java.util.function.Consumer;
11import java.util.function.Function;
12
13public class MySQL {
14 private final BasicDataSource connectionPool;
15
16 public MySQL(BasicDataSource connectionPool) {
17 this.connectionPool = connectionPool;
18 }
19
20 public Connection getConnection() throws SQLException {
21 return connectionPool.getConnection();
22 }
23
24 public void createTables(){
25 Bukkit.getConsoleSender().sendMessage("§e[Hub] §aCréation des tables inexistantes en cours...");
26 update( "CREATE TABLE IF NOT EXISTS accounts (" +
27 "`#` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, " +
28 "uuid VARCHAR(255), " +
29 "pseudo VARCHAR(255)," +
30 "grade VARCHAR(255), " +
31 "grade_end BIGINT, " +
32 "coins BIGINT)"
33 );
34 }
35
36 public void update(String qry){
37 try (Connection c = getConnection();
38 PreparedStatement s = c.prepareStatement(qry)) {
39 s.executeUpdate();
40 } catch(Exception e){
41 e.printStackTrace();
42 }
43 }
44
45 public Object query(String qry, Function<ResultSet, Object> consumer){
46 try (Connection c = getConnection();
47 PreparedStatement s = c.prepareStatement(qry);
48 ResultSet rs = s.executeQuery()) {
49 return consumer.apply(rs);
50 } catch(SQLException e){
51 e.printStackTrace();
52 throw new IllegalStateException(e.getMessage());
53 }
54 }
55
56 public void query(String qry, Consumer<ResultSet> consumer){
57 try (Connection c = getConnection();
58 PreparedStatement s = c.prepareStatement(qry);
59 ResultSet rs = s.executeQuery()) {
60 consumer.accept(rs);
61 } catch(SQLException e){
62 e.printStackTrace();
63 throw new IllegalStateException(e.getMessage());
64 }
65 }
66}