· 5 years ago · Sep 29, 2020, 08:18 PM
1package main.java;
2
3
4import java.sql.*;
5
6
7public class database {
8
9 public Connection ConnectToDb() {
10 Connection conn = null;
11 try {
12 String url = "jdbc:sqlite:data.db";
13 conn = DriverManager.getConnection(url);
14
15 System.out.println("Connectet to SQLite has been established");
16 } catch (SQLException e) {
17 System.out.println(e.getMessage());
18 System.exit(1);
19 }
20 return conn;
21 }
22
23 public void CreateTables(Connection conn) {
24 System.out.println("Creating tables");
25 String sql = "CREATE TABLE IF NOT EXISTS users (UUID text PRIMARY KEY, discordID int NOT NULL );";
26
27 try {
28 if (conn.isClosed()) {
29 conn = ConnectToDb();
30 }
31 Statement stmt = conn.createStatement();
32 stmt.execute(sql);
33 } catch (SQLException e) {
34 System.out.println(e.getMessage());
35 System.exit(1);
36 }
37 }
38
39 public boolean addUserToDB(String uuid, long DiscordID, Connection conn) {
40 String sql = "INSERT INTO users(UUID, discordID) VALUES(?,?)";
41 try {
42 if (conn.isClosed()) {
43 conn = ConnectToDb();
44 }
45 PreparedStatement pstmt = conn.prepareStatement(sql);
46 pstmt.setString(1, uuid);
47 pstmt.setLong(2, DiscordID);
48 pstmt.executeUpdate();
49 return true;
50 } catch (SQLException e) {
51 System.out.println(e.getMessage());
52 return false;
53 }
54 }
55
56 public boolean IsUserInDB(String uuid, Connection conn) {
57 String sql = "SELECT discordID FROM users WHERE UUID = ?";
58 long discordID;
59 try {
60 if (conn.isClosed()) {
61 conn = ConnectToDb();
62 }
63 PreparedStatement pstmt = conn.prepareStatement(sql);
64 pstmt.setString(1, uuid);
65 ResultSet rs = pstmt.executeQuery();
66 discordID = rs.getLong(1);
67 } catch (SQLException e) {
68 System.out.println("User not found");
69 return false;
70 }
71 System.out.println(discordID);
72 return true;
73 }
74
75}
76