Android更快的数据库插入

时间:2012-10-20 19:44:49

标签: android xml sqlite parsing

我正在解析一个包含近20000个标签的巨大xml,我正在解析它们时将xml中的所有条目保存到我的sqlite数据库中。

但显然xml在没有插入操作的情况下很快被解析,但是当我尝试插入每个值时需要很长时间。(大约10分钟)。

数据库插入代码:

for (int i = 0; i < tracksList.size(); i++) {
    dataSource.addTracks(tracksList.get(i));                        
}



public long addTracks(Tracks tracks) {

    long insertId = 0;

    ContentValues values = new ContentValues();
    values.put(TRACKS_ID, tracks.getStrId());
    values.put(TRACKS_ARTISTID, tracks.getStrArtistId());
    values.put(TRACKS_ARTISTNAME, tracks.getStrArtistName());
    values.put(TRACKS_ALBUMNAME, tracks.getStrAlbumName());
    values.put(TRACKS_FILENAME, tracks.getStrFileName());
    values.put(TRACKS_TRACKNAME, tracks.getStrTrackName());

    insertId = database.insert(TRACKS_TABLE, null, values);

    return insertId;
}

是否可以选择从我的arraylist中获取每个元素并以更快的速度保存它们。

编辑:让它工作,thnx all ..

    database.beginTransaction();
    try {
        //standard SQL insert statement, that can be reused
        SQLiteStatement insert = 
                database.compileStatement("insert into " + TRACKS_TABLE
                    + "(" + TRACKS_ID + "," + TRACKS_ARTISTID
                    + "," + TRACKS_ARTISTNAME 
                    + "," + TRACKS_ALBUMNAME 
                    + "," + TRACKS_FILENAME 
                    + "," + TRACKS_TRACKNAME + ")"
                    +" values " + "(?,?,?,?,?,?)");

        for (Tracks value : tracksList){
            //bind the 1-indexed ?'s to the values specified

            System.out.println(value.getStrId());

            insert.bindLong(1, value.getStrId());
            insert.bindString(2, value.getStrArtistId());
            insert.bindString(3, value.getStrArtistName());
            insert.bindString(4, value.getStrAlbumName());
            insert.bindString(5, value.getStrFileName());
            insert.bindString(6, value.getStrTrackName());
            insert.execute();
        }
        database.setTransactionSuccessful();

    } finally {
        database.endTransaction();
    }

1 个答案:

答案 0 :(得分:9)

对所有插入使用一个事务,否则您将获得每个插入的存储同步开销:

database.beginTransaction();
try {
    for (int i = 0; i < tracksList.size(); i++)
        dataSource.addTracks(tracksList.get(i));                        

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