问题
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