Get generated id after insert

后端 未结 5 1455
醉梦人生
醉梦人生 2020-11-27 12:41

I\'m using the SQLite with Android, and I want to know the best way to get the generated id of the row I inserted.

A solution I think makes a search after include, b

5条回答
  •  我在风中等你
    2020-11-27 13:03

    One can simply get last inserted row _id using last_insert_rowid(). Sample code is as below.

    /**
     * Return Last inserted row id(auto incremented row) (_id)
     * @return
     */
    public int getLastAddedRowId() {
        String queryLastRowInserted = "select last_insert_rowid()";
    
        final Cursor cursor = database.rawQuery(queryLastRowInserted, null);
        int _idLastInsertedRow = 0;
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    _idLastInsertedRow = cursor.getInt(0);
                }
            } finally {
                cursor.close();
            }
        }
    
        return _idLastInsertedRow;
    
    }
    

提交回复
热议问题