【问题标题】:How to update "datetime default current_timestamp" with ContentValues?如何使用 ContentValues 更新“日期时间默认 current_timestamp”?
【发布时间】:2016-01-18 19:04:24
【问题描述】:

在 Android 游戏中,用户数据(从不同的社交网络检索)存储在 SQLite 表中:

create table table_social (
        id text primary key,
        social integer not null, /* Facebook = 1, Google+ = 2, Twitter = 3, ... */
        first_name text not null,
        photo text null,
        city text null,
        stamp datetime default current_timestamp /* PROBLEM HERE */
);

应用用户可以将配置文件之一设置为“主要” - 显示在导航抽屉和远程游戏合作伙伴中:

在上面的 SQL 表中,我想通过将配置文件的“stamp”列设置为最新的时间戳来表明配置文件是“main”。

当我需要“主要”配置文件时,我只需调用:

    Cursor cursor = getReadableDatabase().query(TABLE_SOCIAL,
        COLUMNS,
        null,
        null,
        null,
        null,
        "stamp desc",
        "1");

这很好用,但我在通过更新时间戳来更改“主要”配置文件时遇到问题:

public void setMainUser(int social) {
    ContentValues values = new ContentValues();
    values.put(COLUMN_STAMP, (String) null);
    getWritableDatabase().update(TABLE_SOCIAL, 
        values, 
        "social=?", 
        new String[]{ String.valueOf(social) });
}

我也试过

    values.put(COLUMN_STAMP, 0);

但时间戳更新仍未发生。

请有任何建议,如何触发该列的 SQLite“默认”规则?

更新:

作为一种解决方法,我已经尝试过

values.put(COLUMN_STAMP, System.currentTimeMillis() / 1000);

但由于某种原因,该记录尚未更新(我也无法在 Android Studio 调试器中单步执行该部分 - 那里显示了错误的源代码...)

【问题讨论】:

    标签: android sqlite timestamp android-sqlite android-sql


    【解决方案1】:

    仅当您插入一个没有该列值的行时,才会使用默认值。

    更新行时,必须指定新值:

    db.execSQL("UPDATE "+TABLE_SOCIAL+
               " SET "+COLUMN_STAMP+"=CURRENT_TIMESTAMP"+
               " WHERE social=?",
               new Object[]{ social });
    

    CURRENT_TIMESTAMP是SQL关键字,所以不能使用ContentValues。)

    【讨论】:

      猜你喜欢
      • 2012-12-07
      • 1970-01-01
      • 2012-10-05
      • 2012-11-20
      • 2023-01-06
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多