Class DbHelper
contains all database methods. I created a single method for insert to save myself the repetition. When I run my app from the IDE (using the Launcher
main class) it updates the database and does things normally. But when I run the .jar file of my app (an artifact) it doesn't save updates to database (but can read files normally).
I thought it had to do with autocommit set to false, so I set it to true with all update database functions (even though I never explicitly set it to false). I also made sure all ResultSet
variables are closed when I'm done with them. The code that connects to the database:
public static Connection getConnection() {
try {
Class.forName("org.sqlite.JDBC"); // Load the SQLite JDBC driver
String databaseUrl;
// if running .jar file do this
databaseUrl = "jdbc:sqlite::resource:ttlsDatabase.db";
//else (running from ide) do this
//databaseUrl = "jdbc:sqlite:C:\\Users\\medaw\\Desktop\\TTLS_APP\\src\\main\\Resource\\ttlsDatabase.db";
Connection databaseLink = DriverManager.getConnection(databaseUrl);
return databaseLink;
} catch (ClassNotFoundException e) {
System.err.println("SQLite JDBC driver not found. Make sure you have added the SQLite JDBC driver to your project's classpath.");
} catch (SQLException e) {
System.err.println("An error occurred with the database: " + e.getMessage());
}
return null;
}
Whenever I want to run the .jar file I comment out:
databaseUrl = "jdbc:sqlite:C:\\Users\\medaw\\Desktop\\TTLS_APP\\src\\main\\Resource\\ttlsDatabase.db";
Otherwise I comment out:
databaseUrl = "jdbc:sqlite:C:\\Users\\medaw\\Desktop\\TTLS_APP\\src\\main\\Resource\\ttlsDatabase.db";
It worked, I made sure of the con
variable (it's never null) and the data is retrieved from database normally in both cases. I assume the database is in some kind of read only mode.
This is my function which I use to update the database. On advice to optimize this code I'm all ears! I use it for all updates that only require a single execution of a query:
public static boolean updateDatabase(ArrayList<Object> list, String query){
try (Connection con = getConnection()) {
con.setAutoCommit(true);
PreparedStatement stmt = con.prepareStatement(query);
stmt = setStatements(stmt, list);
if (stmt == null) {
return false;
}
int x = stmt.executeUpdate();
if(x == 0){
return false;
}
con.commit();
return true;
} catch (Exception e) {
UtilityMethods.showMessageDialog("Unable to update item!", "Error!", "Update Unsuccessful", 1);
}
return false;
}