Skip to content Skip to sidebar Skip to footer

Using Sqlite Trigger To Update "lastmodified" Field

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 n

Solution 1:

A short and sweet answer for you:

  1. After, so the trigger has a valid table to reference.
  2. You need to execute a CREATE TRIGGER for every table / column combination you want affected. The database won't assume because another table has a last_modified column that you want this one to behave the same...
  3. The trigger in your link is executable (I used it myself), just change the table / column names.

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):

privatestaticfinalStringUPDATE_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:

CREATETRIGGER 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:

CREATETABLE foo (
  _id INTEGERPRIMARY KEY,
  last_modified TIMESTAMPNOTNULLDEFAULT 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.)

Post a Comment for "Using Sqlite Trigger To Update "lastmodified" Field"