[英]Get generated id after insert
我將 SQLite 與 Android 一起使用,我想知道獲取我插入的行的生成 id 的最佳方法。
我認為一個解決方案在包含之后進行搜索,但它看起來並不是最好的方法。
如果使用 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) ;
如果查詢 exec 使用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);
}
我查了資料。 insert
方法使用sqlite3_last_insert_rowid
函數返回一個 id。 根據文檔: https : //www.sqlite.org/c3ref/last_insert_rowid.html行 id 是隱藏列或INTEGER PRIMARY KEY
類型的列(如果已聲明)。
大多數 SQLite 表(
WITHOUT ROWID
表除外)中的每個條目都有一個唯一的64 位有符號整數鍵,稱為“ rowid ”。 rowid 始終可用作名為 ROWID、OID 或 _ROWID_ 的未聲明列,只要這些名稱也沒有被顯式聲明的列使用。 如果表中有一個INTEGER PRIMARY KEY
類型的列,那么該列是rowid 的另一個別名。
所以這通常是默認的_ID
列
我在 mySQL 上遇到了很多問題,LAST_INSERT_ID 不是獲取 ID 的可靠方法,如果您有用戶敲打數據庫,則返回的 ID 可能不是您運行的查詢插入的 ID,有幾個其他用戶可能會影響此 ID 的返回。 我們的服務器每分鍾平均有 7000 名用戶,但它總是跌跌撞撞。
我們的解決方案是使用您插入的查詢中的數據,然后使用該數據搜索該結果。 無論如何,您正在執行查找最后一個 ID 的請求。 所以你不妨做一個 SELECT id FROM table where field=var 和 field=var 來獲取id。 它對查詢的性能略有影響,但返回了更可靠的結果。
可以簡單地使用last_insert_rowid()
獲取最后插入的行 _id 。 示例代碼如下。
/**
* Return Last inserted row id(auto incremented row) (_id)
* @return
*/
public int getLastAddedRowId() {
String queryLastRowInserted = "select last_insert_rowid()";
final Cursor cursor = database.rawQuery(queryLastRowInserted, null);
int _idLastInsertedRow = 0;
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
_idLastInsertedRow = cursor.getInt(0);
}
} finally {
cursor.close();
}
}
return _idLastInsertedRow;
}
long id = db.insert(...);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.