Get last inserted value from sqlite database Android

前端 未结 9 543
不思量自难忘°
不思量自难忘° 2020-11-29 07:11

I am trying to get the last inserted rowid from a sqlite database in Android. I have read a lot of posts about it, but can\'t get one to work. This is my method:



        
相关标签:
9条回答
  • 2020-11-29 08:01

    Use moveToLast() in Cursor interface.

    From android.googlesource.com

    /**
     * Move the cursor to the last row.
     *
     * <p>This method will return false if the cursor is empty.
     *
     * @return whether the move succeeded.
     */
    boolean moveToLast();
    

    Simple example:

    final static String TABLE_NAME = "table_name";
    String name;
    int id;
    //....
    
    Cursor cursor = db.rawQuery("SELECT  * FROM " + TABLE_NAME, null);
    
    if(cursor.moveToLast()){
        //name = cursor.getString(column_index);//to get other values
        id = cursor.getInt(0);//to get id, 0 is the column index
    }
    

    Or you can get the last row when insertion(Which is @GorgiRankovski have mentioned):

    long row = 0;//to get last row
    //.....
    SQLiteDatabase db= this.getWritableDatabase();
    
    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_NAME, name);
    
    row = db.insert(TABLE_NAME, null, contentValues);
    //insert() returns the row ID of the newly inserted row, or -1 if an error occurred 
    

    Also their is a multiple ways you can do this using query:

    1. One is expressed by @DiegoTorresMilano
    2. SELECT MAX(id) FROM table_name. or to get all columns values SELECT * FROM table_name WHERE id = (SELECT MAX(id) FROM table_name).
    3. If your PRiMARY KEY have sat to AUTOINCREMENT, you can SELECT vaules occording to max to min and limit the rows to 1 using SELECT id FROM table ORDER BY column DESC LIMIT 1 (If you want each and every value, use * instead of id)
    0 讨论(0)
  • 2020-11-29 08:10

    I use this

    public int lastId(){
        SQLiteDatabase db =  
      this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from resep", null );
        res.moveToLast();
        return res.getInt(0);
    }
    
    0 讨论(0)
  • 2020-11-29 08:13
    /**
     * @return
     */
    public long getLastInsertId() {
        long index = 0;
        SQLiteDatabase sdb = getReadableDatabase();
        Cursor cursor = sdb.query(
                "sqlite_sequence",
                new String[]{"seq"},
                "name = ?",
                new String[]{TABLENAME},
                null,
                null,
                null,
                null
        );
        if (cursor.moveToFirst()) {
            index = cursor.getLong(cursor.getColumnIndex("seq"));
        }
        cursor.close();
        return index;
    }
    
    0 讨论(0)
提交回复
热议问题