-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseConnection.java
More file actions
105 lines (89 loc) · 2.9 KB
/
DatabaseConnection.java
File metadata and controls
105 lines (89 loc) · 2.9 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
public class DatabaseConnection {
private Connection connection = null;
public DatabaseConnection(String dbFile)
{
try
{
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile);
System.out.println("Database connection successfully established.");
}
catch (ClassNotFoundException cnfex)
{
System.out.println("Class not found exception: " + cnfex.getMessage());
}
catch (SQLException exception)
{
System.out.println("Database connection error: " + exception.getMessage());
}
}
public PreparedStatement newStatement(String query)
{
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(query);
}
catch (SQLException resultsexception)
{
System.out.println("Database statement error: " + resultsexception.getMessage());
}
return statement;
}
public ResultSet runQuery(PreparedStatement statement)
{
try {
return statement.executeQuery();
}
catch (SQLException queryexception)
{
System.out.println("Database query error: " + queryexception.getMessage());
return null;
}
}
public int lastNewID()
{
PreparedStatement statement = Application.database.newStatement("SELECT last_insert_rowid() As 'ID'");
try
{
if (statement != null)
{
ResultSet results = Application.database.runQuery(statement);
if (results != null)
{
return (results.getInt("ID"));
}
}
}
catch (SQLException resultsexception)
{
System.out.println("Database new id retrieval error: " + resultsexception.getMessage());
}
return -1;
}
public void executeUpdate(PreparedStatement statement)
{
try {
statement.executeUpdate();
}
catch (SQLException queryexception)
{
System.out.println("Database update error: " + queryexception.getMessage());
}
}
public void disconnect()
{
System.out.println("Disconnecting from database.");
try {
if (connection != null) connection.close();
}
catch (SQLException finalexception)
{
System.out.println("Database disconnection error: " + finalexception.getMessage());
}
}
}