0

I have a Java program that is connected to a SQLite3 database.
I want to know if there is a way for my program to be notified if a record is added or deleted from a table (not necessarily from my program). I was thinking triggers but can't find any examples of how to hook my Java code to a trigger.

Joe
  • 21
  • 1
  • 2
    You could create a trigger which writes a log entry to a file or other database table. Then, poll that file or table from your Java code. – Tim Biegeleisen Sep 20 '22 at 02:59

1 Answers1

0

You can use the data_version pragma (in any language, not just Java), to see if something else has modified a database.

The integer values returned by two invocations of "PRAGMA data_version" from the same connection will be different if changes were committed to the database by any other connection in the interim. The "PRAGMA data_version" value is unchanged for commits made on the same database connection.

So, basically you execute a PRAGMA data_version statement, which gives you a single row with an integer value that you save. Next time you want to see if something else has modified the database, do it again and compare the old and new numbers to see if they're different.

If you want more of a push notification, you might combine that with the Java NIO WatchService mechanism to watch for changes to the database file (And WAL journal if you're using one), and then check data_version when that triggers. This SO Q&A can hopefully help you get started with that if needed.

Shawn
  • 47,241
  • 3
  • 26
  • 60