Get generated id after insert

后端 未结 5 1440
醉梦人生
醉梦人生 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:01

    If use ContentValues :

     DBHelper db =new DBHelper();// your dbHelper
     ContentValues values = new ContentValues();
      values.put("firstName","Ahmad");
     values.put("lastName","Aghazadeh");
     long insertedId= db.getSQLiteDatabase().insert("user", "", values) ;
    

    If query exec use select last_insert_rowid()

    String sql = "INSERT INTO [user](firstName,lastName) VALUES (\"Ahmad\",\"Aghazadeh\"); select last_insert_rowid()";
     DBHelper itemType =new DBHelper();// your dbHelper
     c = db.rawQuery(sql, null);
     if (c.moveToFirst())
        result = c.getLong(0);
    

    If use Room

    @Entity
    class User {
        @PrimaryKey(autoGenerate = true)
        public int id;
        //...
    }
    
    
    @Dao
    public interface UserDao{
        @Insert(onConflict = OnConflictStrategy.REPLACE)
        long insert(User user);
    
        // Insert multiple users
        @Insert(onConflict = OnConflictStrategy.REPLACE)
        long[] insert(User... user);
    }
    

提交回复
热议问题