Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42860

Get last updated row id

Is there a way to get last updated row id, as what we can get from insert operation?

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;

Upvotes: 0

Views: 3762

Answers (1)

CL.
CL.

Reputation: 180290

The insert function returns the rowid because there is no other way of determining what value was automatically generated by the database.

Updates do not have this problem; the value of the whereClause parameter is already sufficient to find the records. Furthermore, updates might affect more or less than one record, so it is not possible to have a single return value; you need some kind of list for that, so you could just as well use a 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(...);
}

Upvotes: 1

Related Questions