How to get Last record from Sqlite?

前端 未结 12 1994
悲&欢浪女
悲&欢浪女 2020-12-02 07:37

I have a one table question_table and one ImageButton (Back). I need to get the last inserted record from the database after clicking on t

相关标签:
12条回答
  • 2020-12-02 08:15

    Here's a simple example that simply returns the last line without need to sort anything from any column:

    "SELECT * FROM TableName ORDER BY rowid DESC LIMIT 1;"       
    
    0 讨论(0)
  • 2020-12-02 08:20

    To get last record from your table..

     String selectQuery = "SELECT  * FROM " + "sqlite_sequence";
     Cursor cursor = db.rawQuery(selectQuery, null);
      cursor.moveToLast();
    
    0 讨论(0)
  • 2020-12-02 08:24

    If you have already got the cursor, then this is how you may get the last record from cursor:

    cursor.moveToPosition(cursor.getCount() - 1);
    //then use cursor to read values
    
    0 讨论(0)
  • 2020-12-02 08:26

    I think the top answer is a bit verbose, just use this

    SELECT * FROM table ORDER BY column DESC LIMIT 1;
    
    0 讨论(0)
  • 2020-12-02 08:30

    Try this:

    SELECT * 
        FROM    TABLE
        WHERE   ID = (SELECT MAX(ID)  FROM TABLE);
    

    OR

    you can also used following solution:

    SELECT * FROM tablename ORDER BY column DESC LIMIT 1;
    
    0 讨论(0)
  • 2020-12-02 08:31

    Suppose you are looking for last row of table dbstr.TABNAME, into an INTEGER column named "_ID" (for example BaseColumns._ID), but could be anyother column you want.

    public int getLastId() {
        int _id = 0;
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(dbstr.TABNAME, new String[] {BaseColumns._ID}, null, null, null, null, null);
    
        if (cursor.moveToLast()) {
            _id = cursor.getInt(0);
        }
    
        cursor.close();
        db.close();
        return _id;
    }
    
    0 讨论(0)
提交回复
热议问题