Ok, this is the situation. I reused a piece of code from a different project where I checked if a table existed in a certain sqlite db file. If not, it would create the table.
The code worked then and I didn't add major changes to the file, so I am confused that no data is written to the file.
Before I ran the code I had to create an empty database file, which I put src/main/resources, named example.db
public class DBStuff{
protected Connection c = null;
private final String fileName;
public DBStuff(String fileName) {
this.fileName = fileName;
checkDB();
}
protected void startConnection() {
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite::resource:" + fileName);
c.setAutoCommit(false);
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(DBStuff.class.getName()).log(Level.SEVERE, null, ex);
}
}
protected void closeConnection() {
try {
c.close();
} catch (SQLException ex) {
Logger.getLogger(DBStuff.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void checkDB() {
startConnection();
checkTable("firsttable", "CREATE TABLE firsttable"
+ "(id TEXT PRIMARY KEY NOT NULL, "
+ " stuff TEXT NOT NULL)";
checkTable("secondtable", "CREATE TABLE secondtable "
+ "(id TEXT NOT NULL, "
+ " stuffId TEXT NOT NULL, "
+ " specificStuff TEXT NOT NULL, "
+ " CONSTRAINT pk_idstuffId PRIMARY KEY (id,stuffId),"
+ " CONSTRAINT fk_id FOREIGN KEY (id) REFERENCES firsttable(id))");
closeConnection();
}
private void checkTable(String dbName, String sql) {
try {
ResultSet rs;
boolean exists = false;
DatabaseMetaData md = c.getMetaData();
rs = md.getTables(null, null, "%", null);
while (rs.next()) {
if (rs.getString(3).equals(dbName)) {
exists = true;
break;
}
}
if (!exists) {
Statement stmt;
stmt = c.createStatement();
stmt.executeUpdate(sql);
stmt.close();
c.commit();
}
} catch (SQLException ex) {
Logger.getLogger(DBStuff.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I created a DBStuff object using
DBStuff dbstuff = new DBStuff("example.db");
I have verified with print statements that the tables are found when checkDB is run a second time (by printing out rs.getString(3)
).
However when I look in the database file (in all possible locations I could think of, in src/main/resources/example.db
, target/classes/example.db
and inside the warfile in WEB-INF/classes/example.db
), the file is not updated. It is still 0 bytes in size in all those locations.
What am I doing wrong? Why are the tables not written to these files?
I ran the code both with and without this in my pom file
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
I found that the file was actually located in target/ProjectName-x.x.x/WEB-INF/classes/example.db
Tip for me next time: use the search functionality in my file browser. It finds things that you might never find.