【发布时间】:2011-07-21 13:15:38
【问题描述】:
我在 Android 上使用 SQLite,我想知道获取我插入的行的生成 id 的最佳方法。
我认为在包含后进行搜索的解决方案,但它看起来不是最好的方法。
【问题讨论】:
我在 Android 上使用 SQLite,我想知道获取我插入的行的生成 id 的最佳方法。
我认为在包含后进行搜索的解决方案,但它看起来不是最好的方法。
【问题讨论】:
【讨论】:
我检查了来源。
insert 方法使用 sqlite3_last_insert_rowid 函数返回一个 id。
根据文档:https://www.sqlite.org/c3ref/last_insert_rowid.html
行 ID 是隐藏列或 INTEGER PRIMARY KEY 类型的列(如果已声明)。
大多数 SQLite 表(
WITHOUT ROWID表除外)中的每个条目都有一个 唯一 64 位有符号整数 key,称为“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 and field=var 来获取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) ;
如果查询执行使用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);
}
【讨论】:
使用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;
}
【讨论】: