SQL timestamp does not change when UPDATE happens

我的梦境 提交于 2019-12-24 03:16:06

问题


I use the following SQL command to create a products table on an Android client.

CREATE TABLE IF NOT EXISTS 'products' (
  '_id' INTEGER PRIMARY KEY AUTOINCREMENT,
  'name' TEXT,
  'serverId' INTEGER, 
  'modifiedAt' TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 
  UNIQUE ( 'serverId' ) 
ON CONFLICT REPLACE );

When I load data from a server and insert it into the local database, I use the following commands in the content provider to either update a row or insert new values.

public int bulkInsert(Uri uri, ContentValues[] values) {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    long rowId;
    int rowsAdded = 0;
    for (ContentValues contentValues : values) {
        int affectedRows = db.update("products", contentValues, 
                "serverId = ?", 
                new String[] { contentValues.getAsString("serverId") });
        if (affectedRows == 0) {
            rowId = db.insert("products", null, contentValues);
            if (rowId > 0) {
                rowsAdded++;
            }
        }
    }
    return rowsAdded;
}

All columns are updated when new values are there, except the column modifiedAt.
Note: The bulk commands are wrapped into a transaction. I left out the code to keep the question simple.

Question:

How can I update the timestamp of the modifiedAt column every time an update happens?


回答1:


You could let the database handle that by setting up triggers:

Untested...

database.execSQL("CREATE TRIGGER updateLastModifiedDate " +
     "AFTER INSERT ON products FOR EACH ROW BEGIN " +
     "UPDATE products SET modifiedAt = date('now') " +
     "WHERE _id = NEW.id " +
     "END;");

database.execSQL("CREATE TRIGGER updateLastModifiedDate " +
     "AFTER UPDATE ON products FOR EACH ROW BEGIN " +
     "UPDATE products SET modifiedAt = date('now') " +
     "WHERE _id = NEW.id " +
     "END;");


来源:https://stackoverflow.com/questions/12013563/sql-timestamp-does-not-change-when-update-happens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!