简体   繁体   English

插入后获取生成的id

[英]Get generated id after insert

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.我将 SQLite 与 Android 一起使用,我想知道获取我插入的行的生成 id 的最佳方法。

A solution I think makes a search after include, but it doesn't look the best way.我认为一个解决方案在包含之后进行搜索,但它看起来并不是最好的方法。

"

The insert method returns the id of row just inserted or -1 if there was an error during insertion. insert方法返回刚刚插入的行的id ,如果插入过程中出现错误,则返回-1

long id = db.insert(...);

where db is SQLiteDatabase .其中 db 是SQLiteDatabase

If use ContentValues :如果使用 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()如果查询 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);

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);
}

I checked the sources.我查了资料。 insert method use sqlite3_last_insert_rowid function to return an id. insert方法使用sqlite3_last_insert_rowid函数返回一个 id。 According to the documentation: https://www.sqlite.org/c3ref/last_insert_rowid.html The row id is the hidden column or a column of type INTEGER PRIMARY KEY if it's declared.根据文档: https : //www.sqlite.org/c3ref/last_insert_rowid.html行 id 是隐藏列或INTEGER PRIMARY KEY类型的列(如果已声明)。

Each entry in most SQLite tables (except for WITHOUT ROWID tables) has a unique 64-bit signed integer key called the " rowid ".大多数 SQLite 表( WITHOUT ROWID表除外)中的每个条目都有一个唯一的64 位有符号整数键,称为“ 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. rowid 始终可用作名为 ROWID、OID 或 _ROWID_ 的未声明列,只要这些名称也没有被显式声明的列使用。 If the table has a column of type INTEGER PRIMARY KEY then that column is another alias for the rowid .如果表中有一个INTEGER PRIMARY KEY类型的列,那么该列是rowid 的另一个别名

So that is the default _ID column usually所以这通常是默认的_ID

I had quite a bit of problems with this on mySQL, the LAST_INSERT_ID is not reliable way to get the ID, if you have users hammering the database, the ID returned may not be the ID that was inserted by the query you have run, several other users might impact on the return of this id.我在 mySQL 上遇到了很多问题,LAST_INSERT_ID 不是获取 ID 的可靠方法,如果您有用户敲打数据库,则返回的 ID 可能不是您运行的查询插入的 ID,有几个其他用户可能会影响此 ID 的返回。 We had server with average of 7000 users a minute hammering away and it always stumbled.我们的服务器每分钟平均有 7000 名用户,但它总是跌跌撞撞。

The solution we had was to use data from the query you inserted, and then search for that result using that data.我们的解决方案是使用您插入的查询中的数据,然后使用该数据搜索该结果。 You are doing a request looking for last id anyway.无论如何,您正在执行查找最后一个 ID 的请求。 So you might as well do a SELECT id FROM table where field=var and field=var to get the id.所以你不妨做一个 SELECT id FROM table where field=var 和 field=var 来获取id。 Its a slight performance hit on the query, but a much more reliable result returned.它对查询的性能略有影响,但返回了更可靠的结果。

One can simply get last inserted row _id using last_insert_rowid() .可以简单地使用last_insert_rowid()获取最后插入的行 _id 。 Sample code is as below.示例代码如下。

/**
 * 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM