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) ;
如果查询执行使用 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);
如果使用房间
@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);
}