Get generated id after insert
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
@Entityclass User { @PrimaryKey(autoGenerate = true) public int id; //...}@Daopublic interface UserDao{ @Insert(onConflict = OnConflictStrategy.REPLACE) long insert(User user); // Insert multiple users @Insert(onConflict = OnConflictStrategy.REPLACE) long[] insert(User... user);}
I checked the sources.insert
method use sqlite3_last_insert_rowid
function to return an id.According to the documentation: https://www.sqlite.org/c3ref/last_insert_rowid.htmlThe row id is the hidden column or a column of type INTEGER PRIMARY KEY
if it's declared.
Each entry in most SQLite tables (except for
WITHOUT ROWID
tables) has a unique 64-bit signed integer key called the "rowid". The rowid is always available as an undeclared column named ROWID, OID, or _ROWID_ as long as those names are not also used by explicitly declared columns. If the table has a column of typeINTEGER PRIMARY KEY
then that column is another alias for the rowid.
So that is the default _ID
column usually