-
Notifications
You must be signed in to change notification settings - Fork 0
/
Database.java
63 lines (58 loc) · 1.87 KB
/
Database.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Organised.
* Copyright (c) 2021, Agne Knietaite
* All rights reserved.
*
* This source code is licensed under the GNU General Public License, Version 3
* found in the LICENSE file in the root directory of this source tree.
*
* Class which handles Database initialization and connections.
*/
public class Database {
private final static String URL = "jdbc:sqlite::resource:database/organisedDB.db";
private static Connection connection = null;
/**
* Opens a connection to the SQLite Database
*/
public static void openConnection() {
try{
connection = DriverManager.getConnection(URL);
}
catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Connection opened to " + URL);
}
/**
* Closes the connection stored by Database.connection.
*/
public static void closeConnection() {
if(connection == null) {
// If no connection to close, throw error
throw new RuntimeException("Current connection is null, no database connection to close.");
}else {
try {
connection.close();
System.out.println("Connection closed from " + URL);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* Getter for Database.connection, only returns if a connection has already been previously opened.
*
* @return Connection instance
*/
public static Connection getConnection() {
// If no connection is present, throw exception
if(connection != null) return connection;
else {
throw new RuntimeException("Current connection is null. Start with Database.openConnection()");
}
}
}