This might be more of a design question, but here goes. I'm writing an Android app that uses a local SQLite database (with multiple tables) that syncs with a MySQL database every now-and-then. I only want to update modified rows in my database. To do this, I'm adding a column "last_modified
" to each row that indicates the time when that row was added/updated/replaced/etc.
I'm new to database operations, but I've seen that a Trigger might be the best way to do this. I have a couple questions relating to Triggers, SQLite, and Android.
I've read this link: on update current_timestamp with SQLite It basically says that I'm using the right approach. My questions are:
db.execSQL("CREATE TRIGGER...")
statement? Before or after I create the tables?last_modified
" field, or do I have to create a separate Trigger for each table?Or if Triggers are a bad idea, are there any better alternatives?
Thank you.
Triggers are database operations that are automatically performed when a specified database event occurs. Each trigger must specify that it will fire for one of the following operations: DELETE, INSERT, UPDATE. The trigger fires once for each row that is deleted, inserted, or updated.
The SQLite UPDATE statement is used to update existing records in a table in a SQLite database. There are 2 syntaxes for the UPDATE statement depending on the type of update that you wish to perform.
SQLite trigger may be specified to fire whenever a DELETE, INSERT or UPDATE of a particular database table occurs or whenever an UPDATE occurs on one or more specified columns of a table. At this time, SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers.
A short and sweet answer for you:
last_modified
column that you want this one to behave the same...Lastly, using a trigger like this is the easiest way I know to maintain last_modified
or last_accessed
timestamp.
My trigger (in java form):
private static final String UPDATE_TIME_TRIGGER =
"CREATE TRIGGER update_time_trigger" +
" AFTER UPDATE ON " + TABLE_NAME + " FOR EACH ROW" +
" BEGIN " +
"UPDATE " + TABLE_NAME +
" SET " + TIME + " = current_timestamp" +
" WHERE " + ID + " = old." + ID + ";" +
" END";
Addition
According to the SQLite website you need to create a trigger for each type of action. In other words, you cannot use:
CREATE TRIGGER trigger_name
AFTER UPDATE, INSERT ...
From your last comment you may have figured out the best way to handle an INSERT statement for our purpose:
CREATE TABLE foo (
_id INTEGER PRIMARY KEY,
last_modified TIMESTAMP NOT NULL DEFAULT current_timstamp);
In this table, you do not need to create a timestamp trigger for an INSERT statement, since it is done already. (Fun fact: INTEGER PRIMARY KEY
implicitly adds AUTOINCREMENT NOT NULL
as well as the default incremental value to our _id
column.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With