· 6 years ago · Jul 23, 2019, 03:56 PM
1
2 protected static final String CREATE = "CREATE TABLE IF NOT EXISTS [table] (UniqueId VARCHAR(255) NOT NULL PRIMARY KEY, Json LONGTEXT)";
3 protected static final String LOAD = "SELECT Json FROM [table]";
4
5 protected static final String TABLE = "[table]";
6 protected String getQuery(String query) {
7 return query.replace(TABLE, dataObject.getSimpleName());
8 }
9
10 @Override
11 public void createTable() throws DatabaseException {
12 String query = getQuery(CREATE);
13 try(Connection conn = getPlugin().getDataStorage().getConnection();
14 PreparedStatement statement = conn.prepareStatement(query)) {
15 statement.execute();
16 } catch(Exception e) {
17 throw new DatabaseException(e);
18 }
19 }
20
21 public List<T> loadObjects() {
22 String query = getQuery(LOAD);
23 try(Connection conn = getPlugin().getDataStorage().getConnection();
24 PreparedStatement statement = conn.prepareStatement(query)) {
25 ResultSet result = statement.executeQuery();
26 // FAI COSE
27 List<T> objects = new ArrayList<>();
28 while(result.next()) {
29 objects.add(this.getGson().fromJson(result.getString("Json"), dataObject));
30 }
31 return objects;
32 } catch (DatabaseException | SQLException e) {
33 getStoreLoader().getLogger().severe("Failed load objects from the database...");
34 getStoreLoader().getLogger().severe("Error: " + e.getMessage());
35 e.printStackTrace();
36 return null;
37 }
38 }