在迭代游标时从Android SQLite数据库中删除行是否安全

时间:2014-01-06 15:41:47

标签: java android sqlite cursor

例如:

public void removeStaleMovies(Set<String> updatedMovieList) {
    Cursor cur = this.getReadableDatabase().rawQuery("SELECT id, title, year FROM movie", null);
    cur.moveToFirst();
    while (!cur.isAfterLast()) {
        String title = cur.getString(1);
        String year = cur.getString(2);
        if (!updatedMovieList.contains(title + "-" + year)) {
              // delete the row where 'id' = cur.getString(0)
              // OR, delete the row using the object at the cursor's current position, if that's possible
              // OR, if deletion isn't safe while iterating, build up a list of row id's and run a DELETE statement after iteration is finished    
        }

    }
}

删除是否安全?或者它会导致一些不可预测的行为?我知道this similar question,但我仍然不确定。

1 个答案:

答案 0 :(得分:8)

从代码安全的角度来看,这应该没问题,假设查询的结果集小于1MB。在这种情况下,Cursor在堆空间中保存整个结果集,因此它与基础数据库的任何更改都是隔离的。

话虽这么说,你可能想要建立一个要删除的行列表,这样你就可以在一个语句中删除它们,而不是一堆单独的语句(尽管在事务中包装那些单独的语句可能会给你类似的表现特征)。