【问题标题】:Get generated id after insert插入后获取生成的id
【发布时间】:2011-07-21 13:15:38
【问题描述】:

我在 Android 上使用 SQLite,我想知道获取我插入的行的生成 id 的最佳方法。

我认为在包含后进行搜索的解决方案,但它看起来不是最好的方法。

【问题讨论】:

    标签: java android sqlite


    【解决方案1】:

    insert 方法返回刚刚插入的行的id,如果插入过程中出现错误,则返回-1

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

    其中 db 是 SQLiteDatabase

    【讨论】:

    • 我阅读了规格。 “返回:新插入行的行ID,如果发生错误,则为-1”rowId与我生成的字段“id主键自动增量”相同?
    • @GrAnd,但是如果我要删除表中的一些“start-middle”行怎么办,所以我用生成的 id=n 打破第 n 行的序列。返回的行 ID 是否与生成的自动增量 ID 保持一致?
    • 我找不到答案,如果 long id = -1 值,那错误代码是什么?
    • 如果您需要执行 INSERT OR UPDATE 并获取 id 怎么办?
    • @UnknownJoe 我知道这是旧帖子。但可能对某人有帮助。即使从中间删除,行 id 和自增 id 也会相同。
    【解决方案2】:

    我检查了来源。 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

    【讨论】:

      【解决方案3】:

      我在 mySQL 上遇到了很多问题,LAST_INSERT_ID 不是获取 ID 的可靠方法,如果您有用户敲击数据库,返回的 ID 可能不是您的查询插入的 ID运行,其他几个用户可能会影响这个 id 的返回。我们的服务器平均每分钟有 7000 名用户在运行,但它总是出现故障。

      我们的解决方案是使用您插入的查询中的数据,然后使用该数据搜索该结果。无论如何,您正在执行寻找最后一个 id 的请求。所以你不妨做一个 SELECT id FROM table where field=var and field=var 来获取id。它对查询的性能有轻微影响,但返回的结果要可靠得多。

      【讨论】:

      • 这要求每行的列值是唯一的(或大部分是唯一的),否则可能会返回多个 ID。
      【解决方案4】:

      如果使用 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);
      }
      

      【讨论】:

        【解决方案5】:

        使用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;
        
        }
        

        【讨论】:

        猜你喜欢
        • 2011-04-03
        • 2013-10-06
        • 1970-01-01
        • 2019-08-04
        • 2019-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多