【问题标题】:Get last updated row id获取最后更新的行 id
【发布时间】:2014-05-09 19:21:26
【问题描述】:

有没有办法获取最后一个更新的行ID,就像我们可以从insert操作中得到的那样?

Get generated id after insert

int row_id = -1

// fx_watchlist_id is having constraint unique (fx_watchlist_id) on conflict.
// So, we are pretty sure maximum updated row will be 1
int count = database.update(TABLE_TIMESTAMP, values, "fx_watchlist_id = ?", new String[]{Long.toString(fxWatchlistId)});
if (count <= 0) {
    row_id = database.insert(TABLE_TIMESTAMP, null, values);
} else {
    // Is there a way to retrieve last updated row id, without perform select?
    row_id = ...
}

return row_id;

【问题讨论】:

    标签: android sqlite


    【解决方案1】:

    insert 函数返回 rowid,因为没有其他方法可以确定数据库自动生成的值。

    更新没有这个问题; whereClause 参数的值已经足以找到记录。 此外,更新可能会影响更多或更少的记录,因此不可能有单个返回值;你需要一些列表,所以你也可以使用Cursor

    Cursor c = database.query(TABLE_TIMESTAMP, new String[] { "rowid" },
                              "fx_watchlist_id = " + fxWatchlistId, null,
                              null, null, null);
    if (c.moveToFirst()) {
        row_id = c.getLong(0);
        database.update(TABLE_TIMESTAMP, values,
                        "rowid = " + row_id, null);
    } else {
        row_id = database.insert(...);
    }
    

    【讨论】:

    • 如果使用这种方法,这里的关键是查询即将更新的行执行实际更新之前,因为update 操作可能很好地改变 where 约束中字段的值,例如UPDATE myTable SET col1=2 WHERE col1=1。使用原始 where 子句 (col1=1) 查询 之后 在这种情况下更新将返回一个空游标。
    猜你喜欢
    • 2010-11-26
    • 2015-01-03
    • 2013-12-17
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 2019-09-19
    相关资源
    最近更新 更多