Get last inserted value from sqlite database Android

前端 未结 9 542
不思量自难忘°
不思量自难忘° 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 07:53

    Well actually the SQLiteDatabase class has its own insert method which returns the id of the newly created row. I think this is the best way to get the new ID. You can check its documentation here.

    I hope this helps.

    0 讨论(0)
  • 2020-11-29 07:55

    Use

     SELECT last_insert_rowid();
    

    to get the last inserted rowid. If you are using AUTOINCREMENT keyword then

    SELECT * from SQLITE_SEQUENCE;
    

    will tell you the values for every table.

    0 讨论(0)
  • 2020-11-29 07:56

    If you want the last_insert_id just afert a insert you can use that :

    public long insert(String table, String[] fields, String[] vals ) 
    {
        String nullColumnHack = null;
        ContentValues values = new ContentValues();
        for (int i = 0; i < fields.length; i++) 
        {
            values.put(fields[i], vals[i]); 
        }
    
        return myDataBase.insert(table, nullColumnHack, values);
    }
    
    0 讨论(0)
  • 2020-11-29 07:56

    The insert method returns the id of row just inserted or -1 if there was an error during insertion.

    long id = db.insert("your insertion statement");
    

    db is an instance of your SQLiteDatabase.

    0 讨论(0)
  • 2020-11-29 07:59

    To get the last row from the table..

    Cursor cursor = theDatabase.query(DATABASE_TABLE, columns,null, null, null, null, null);
    cursor.moveToLast();
    
    0 讨论(0)
  • 2020-11-29 08:01

    Try this:

    public Cursor getLastId() {
            return mDb.query(DATABASE_TABLE, new String[] { **MAX(id)** }, null, null, null, null, null, null);}
    
    0 讨论(0)
提交回复
热议问题