我正在解析一个包含近 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;
}
是否有任何替代方法可以从我的数组列表中获取每个元素并以更快的速度保存它们。
编辑:得到它的工作,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();
}