I'm trying to avoid static and Singletons while integrating a local H2 database into my JavaFX app (Java8). Five other classes (including Controllers) require access to the database so I'm trying to share the one H2 connection between them all. I've read a Connection Pool avoids unnecessary reconnects, but am confused if it's applicable here. Desktop use, single user.
The following ExtrasDB
Class contains 3 methods, initializeDB
, getDBValues
and performQuery
. Previously these methods were static
and I would call them from other classes using ExtrasDB.getDBValues()
and use the result accordingly, but since my application uses multiple threads I'm looking for a better approach. I'm in the process of removing all static/Singleton use from my app.
The initializeDB
method creates the connection and creates a table if necessary, and this method is called only once from my main controller's initialize
method. This causes the connection conn
to be isolated to that instance and not accessible to other class's calls on getDBValues
or performQuery
which causes null result sets. How do I make the database connection accessible to all necessary classes, so that these classes can freely access the database using the methods above?
public class ExtrasDB {
final String JDBC_DRIVER = "org.h2.Driver";
final String DB_URL = "jdbc:h2:~/mainDB";
final String USER = "test";
final String PASS = "test";
Connection conn = null;
Statement statement = null;
String myStatement;
ResultSet rs;
DatabaseMetaData meta;
public void initializeDB() {
try {
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected to database successfully...");
statement = conn.createStatement();
meta = conn.getMetaData();
rs = meta.getTables(null, null, "EXTRAS", new String[]{"TABLE"}); // <--- Checks for existence of table "EXTRAS"
if (!rs.next()) {
System.out.println("Table doesn't exist yet... Creating...");
sql = "CREATE TABLE EXTRAS " +
"(column_1 VARCHAR(255), " +
" column_2 VARCHAR(255))";
statement.executeUpdate(sql);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void getDBValues() throws SQLException {
rs = statement.executeQuery("SELECT * FROM EXTRAS");
while (rs.next()) {
//..... do something
}
}
public void performQuery(String query) {
try {
statement.executeUpdate(query);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}