· 4 years ago · Mar 01, 2021, 11:42 PM
1package de.nick.smartclans;
2
3import org.sqlite.SQLiteDataSource;
4
5import java.io.File;
6import java.io.IOException;
7import java.sql.SQLException;
8import java.sql.Statement;
9
10
11public class DatabaseHandler {
12
13 final private SQLiteDataSource ds;
14
15 public DatabaseHandler() {
16 ds = new SQLiteDataSource();
17 }
18
19 @SuppressWarnings("ResultOfMethodCallIgnored")
20 public boolean init(String path, String filename){
21 File dir = new File(path);
22 dir.mkdirs();
23 File database = new File(path, filename);
24 try {
25 database.createNewFile();
26 } catch (IOException e) {
27 e.printStackTrace();
28 return false;
29 }
30 ds.setUrl("jdbc:sqlite:" + database.getPath());
31 return true;
32 }
33
34 public SQLiteDataSource getDatasource() {
35 return ds;
36 }
37
38 public void createTables(){
39 try {
40 Statement st = ds.getConnection().createStatement();
41 String sql = "CREATE TABLE IF NOT EXISTS clans (Name varbinary(16), Leader varbinary(16));";
42 st.execute(sql);
43 if(!doesColumnExist("clans", "test")) {
44 st.execute("ALTER TABLE clans ADD COLUMN test varbinary(16)");
45 }
46 } catch (SQLException e) {
47 e.printStackTrace();
48 }
49 }
50
51 private boolean doesColumnExist(String tableName, String columnName) throws SQLException {
52 Statement st = ds.getConnection().createStatement();
53 try{
54 st.execute("SELECT " + columnName + " FROM " + tableName);
55 }catch (SQLException e) {
56 return false;
57 }
58 return true;
59 }
60}