Android 在遍历游标时插入数据库

Android 在遍历游标时插入数据库,android,database,sqlite,insert,android-cursor,Android,Database,Sqlite,Insert,Android Cursor,我有一个包含数据库中3列的游标。我需要遍历,并将ID添加到另一个表中。我尝试使用下面的代码,但它导致应用程序没有响应消息,并且花了大约10秒的时间插入大约1000行的所有行 我已经修改了代码,这样我就可以遍历游标并分别插入到数据库中,现在需要大约500毫秒的时间。虽然我似乎已经解决了我的问题,但我不明白为什么 有人能解释一下为什么下面的代码需要这么长时间才能执行吗 public void setNowPlayingSongs(SQLiteDatabase db, Cursor cursor) {

我有一个包含数据库中3列的游标。我需要遍历,并将ID添加到另一个表中。我尝试使用下面的代码,但它导致应用程序没有响应消息,并且花了大约10秒的时间插入大约1000行的所有行

我已经修改了代码,这样我就可以遍历游标并分别插入到数据库中,现在需要大约500毫秒的时间。虽然我似乎已经解决了我的问题,但我不明白为什么

有人能解释一下为什么下面的代码需要这么长时间才能执行吗

public void setNowPlayingSongs(SQLiteDatabase db, Cursor cursor) {
    // Clear all the current songs
    db.delete(TABLE_NOW_PLAYING, null, null);

    ContentValues cv = new ContentValues();
    cursor.moveToFirst();

    int index = cursor.getColumnIndex(COL_ID);

    while (!cursor.isAfterLast()){
        cv.put(COL_SONG_ID, cursor.getInt(index));
        db.insert(TABLE_NOW_PLAYING, null, cv);
        cursor.moveToNext();
    }

}
为什么这么快?我不明白为什么循环光标然后循环列表会更快。我觉得上面的方法应该快一点

public void setNowPlayingSongs(SQLiteDatabase db, Cursor cursor) {
    ContentValues cv;
    List<Integer> ids;
    int index;

    // Clear all the current songs
    db.delete(TABLE_NOW_PLAYING, null, null);

    // Check which column holds the IDs
    index = cursor.getColumnIndex(COL_ID);

    // Add the ids to a list
    ids = new ArrayList<Integer>();
    cursor.moveToFirst();        
    while (!cursor.isAfterLast()) {
        ids.add(cursor.getInt(index));
        cursor.moveToNext();
    }

    // Insert the IDs into the now playing table.
    cv = new ContentValues();
    db.beginTransaction();
    for (Integer id : ids) {
        cv.put(COL_SONG_ID, id);
        db.insert(TABLE_NOW_PLAYING, null, cv);
    }
    db.setTransactionSuccessful();
    db.endTransaction();
}

当您执行单个插入时,每个插入实际上都包装在一个SQLite事务中。如果您改为在一个事务中执行所有插入,这将大大加快速度

db.beginTransaction();
try {
    // do your inserts

    db.setTransactionSuccessful();
} finally {
    db.endTransaction();
}

我确实这样做了,虽然它加快了速度,但仍然需要6或7秒。唯一有效的方法是循环遍历游标,首先将ID添加到列表中,然后循环遍历列表以插入db,但我不明白为什么在1000个ID中循环两次比我原来的方法快,使用原始insert语句将大大提高性能@karakuri@arul你说得有点对。您可以通过在每次迭代中使用和绑定新值来加快这一过程。通常,SQLiteDatabase必须准备语句并绑定参数,因此您可以通过不让语句反复准备相同的语句来保存。