【问题标题】:Android SqlLite update last inserted rowAndroid Sqlite 更新最后插入的行
【发布时间】:2013-03-06 12:46:22
【问题描述】:

这是我用来插入的:

 public long insert(String content, Date startAt, Date endAt) {
        if (content == null || startAt == null) {
            return 0;
        }

        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_CONTENT, content);
        contentValues.put(KEY_START_AT, startAt.getTime());
        if (endAt == null) {
            contentValues.putNull(KEY_END_AT);
        } else {
            contentValues.put(KEY_END_AT, endAt.getTime());
        }

        return sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
    }

现在我想创建更新方法来更新最后插入的行。我怎样才能得到最后插入的行?

【问题讨论】:

标签: android


【解决方案1】:

如果您有一个用作主键的 id 属性,您可以在 SqlLite 上执行原始数据库查询。

Cursor cc = this.mDb.rawQuery("SELECT *" + " FROM " + "<Your DATABASE_NAME> " + 
"ORDER BY id " + "DESC LIMIT 1", null);
return cc;

这里, 1.它返回一个游标。 2. mDb 是一个 SQLiteDatabase 类实例。 3. ORDER BY id 允许查询按id号排序。正如我所说,如果您的表中有一个 id 作为主键,那么您的最新条目将具有最大的 id 编号。 4. DESC 允许按降序排序。 5. LIMIT 1 只允许返回 1 行。 6. 编写原始查询时要小心,如果不小心处理查询中的空格,可能会很痛苦。

如需进一步查询,您可以查看this 教程。而且很明显 Divya 的回答也不错。

【讨论】:

    【解决方案2】:

    您可以使用cursor 检索行并说:

       cursor.moveToLast();
    

      cursor.moveToPosition(cursor.getCount() - 1);
    

    【讨论】:

      【解决方案3】:

      当您在表中插入一行时,插入查询会返回最后插入行的键。您现在可以使用此键更新此行。

      例如

      int newInsertedKey = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);

      update table_name set column_name = 'Change 2' where columnID = newInsertedKey

      一种有效的方法是避免数据库查询以获取最后更新的行。

      【讨论】:

        【解决方案4】:

        也许他应该使用这样的东西

        public long getLastId() {
            Cursor c = mDb.query(currentTableName, new String[] { "MAX(_id)" },
                    null, null, null, null, null, null);
        
                    try{
            c.moveToFirst();
            long id = c.getLong(0);
            return id;
                    }catch(Exception e){
                      return 0;
                    }
        

        }

        其中 _id 是用于识别行的列

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-10-29
          • 2011-12-21
          • 2016-06-15
          • 2011-11-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多