简体   繁体   中英

Is it safe to delete rows from Android SQLite database while iterating cursor

For example:

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    
        }

    }
}

Is deletion safe to do? Or can it result in some unpredictable behavior? I am aware of this similar question , but I'm still unsure.

From a code safety standpoint, this should be OK, assuming that the result set of your query is less than 1MB. In that case, the Cursor holds in heap space the entire result set, so it is insulated from any changes to the underlying database.

That being said, you may want to build up a list of rows to delete, simply so you can delete them in a single statement, rather than a bunch of individual statements (though wrapping those individual statements in a transaction may give you similar performance characteristics).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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