· 8 years ago · Mar 05, 2018, 05:36 PM
1Connection con = null;
2try{
3 String url = "jdbc:sqlite:PATH/TO/SQLITE/FILE.db"
4 conn = DriverManager.getConnection(url);
5 //Log that SQLite connection has been established
6}catch(SQLException e){
7 //Log that SQLite connection has failed, and terminate the plugin
8 //print e.getmessage();
9}finally{
10 try{
11 conn.close()
12 }catch(SQLException e){
13 //print e.getMessage();
14 }
15}
16
17
18//Table creation
19//Original SQL command to enable Foregn keys:
20//SQL command: PRAGMA foreign_keys = ON;
21connection.createStatement().execute("PRAGMA foreign_keys = ON");
22//create the players table
23//SQL command: CREATE TABLE IF NOT EXISTS doorsPlugin.player (playerUUID TEXT PRIMARY KEY) UNIQUE(playerUUID) WITHOUT ROWID ON CONFLICT IGNORE;
24//create the doors table
25//SQL command: CREATE TABLE IF NOT EXISTS doorsPlugin.door (doorID INT PRIMARY KEY AUTOINCREMENT, otherInformation STRING) UNIQUE(doorID);
26//create the doorplayerunion table
27//SQL command: CREATE TABLE IF NOT EXISTS doorsPlugin.doorPlayerUnion (FOREIGN KEY (playerUUID) REFERENCES doorsPlugin.player(playerUUID), FOREIGN KEY (doorID) REFERENCES doorsPlugin.door(doorID));
28
29
30//Get players
31//Get playerUUID from elsewhere
32String playerUUID = somethingfromsomwhere;
33("SELECT * FROM players WHERE player = '" + playerUUID + "';");
34Resultset rs = ps.executeQuery();
35boolean playerInDB = false;
36playerInDB = rs.getString("player").equals(playerUUID);
37if(!playerInDB){
38 //SQL command: INSERT INTO player(playerUUID) VALUES(?)
39 String playerInsertsql = "INSERT INTO player(playerUUID) VALUES(?)"
40 try{
41 conn = DriverManager.getConnection(url);
42 PreparedStatement playerstatement = conn.prepareStatement(playerInsertsql){
43 statement.setString(1,playerUUID)
44 statement.executeUpdate();
45 }
46 conn.close();
47 }catch(SQLException e){
48 //print e.getMessage();
49 }
50}
51
52
53//adding a door
54//Door id will be fetched from the SQL db after door creation, so we don't need to fetch it here.
55String doorInsertsql = "INSERT INTO door(doorID,othervalue,othervalue2,...) VALUES(?,?,?,...)"
56try{
57 conn = DriverManager.getConnection(url);
58 PreparedStatement doorstatement = conn.prepareStatement(doorInsertsql){
59 //ID is auto-incremented, so we'll have to fetch that in a bit.
60 //Insert all of your door data here
61 /*
62 statement.setString(argument number(in this case, 1), STRING CONTENTS);
63 statement.setInt(argument number(in this case, 2), contents);
64 setDouble, setwhatever, same deal.
65 */
66 }
67 //Now we need to get that door id
68 SQLCommand cmd = new SqlCommand("SELECT last_insert_rowid()",conn);
69 int lastID = (Int32)cmd.ExecuteScalar();
70 //LastID is now the ID of your door. When loading from DB at server start, this should be easier.
71catch(SQLException e){
72 //print e.getMessage()
73}
74
75
76//Now make the Union
77String doorPlayerUnionsql = "INSERT INTO doorPlayerUnion