Android批量插入數(shù)據(jù)到SQLite數(shù)據(jù)庫
Android中在sqlite插入數(shù)據(jù)的時(shí)候默認(rèn)一條語句就是一個(gè)事務(wù),因此如果存在上萬條數(shù)據(jù)插入的話,那就需要執(zhí)行上萬次插入操作,操作速度可想而知。因此在Android中插入數(shù)據(jù)時(shí),使用批量插入的方式可以大大提高插入速度。
有時(shí)需要把一些數(shù)據(jù)內(nèi)置到應(yīng)用中,常用的有以下2種方式:其一直接拷貝制作好的SQLite數(shù)據(jù)庫文件,其二是使用系統(tǒng)提供的數(shù)據(jù)庫,然后把數(shù)據(jù)批量插入。我更傾向于使用第二種方式:使用系統(tǒng)創(chuàng)建的數(shù)據(jù)庫,然后批量插入數(shù)據(jù)。批量插入數(shù)據(jù)也有很多方法,那么那種方法更快呢,下面通過一個(gè)demo比較一下各個(gè)方法的插入速度。
1、使用db.execSQL(sql)
這里是把要插入的數(shù)據(jù)拼接成可執(zhí)行的sql語句,然后調(diào)用db.execSQL(sql)方法執(zhí)行插入。
public void inertOrUpdateDateBatch(List<String> sqls) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { for (String sql : sqls) { db.execSQL(sql); } // 設(shè)置事務(wù)標(biāo)志為成功,當(dāng)結(jié)束事務(wù)時(shí)就會(huì)提交事務(wù) db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); } finally { // 結(jié)束事務(wù) db.endTransaction(); db.close(); } } |
2、使用db.insert("table_name", null, contentValues)
這里是把要插入的數(shù)據(jù)封裝到ContentValues類中,然后調(diào)用db.insert()方法執(zhí)行插入。
db.beginTransaction(); // 手動(dòng)設(shè)置開始事務(wù) for (ContentValues v : list) { db.insert("bus_line_station", null, v); } db.setTransactionSuccessful(); // 設(shè)置事務(wù)處理成功,不設(shè)置會(huì)自動(dòng)回滾不提交 db.endTransaction(); // 處理完成 db.close() |
3、使用InsertHelper類
這個(gè)類在API 17中已經(jīng)被廢棄了
InsertHelper ih = new InsertHelper(db, "bus_line_station"); db.beginTransaction(); final int directColumnIndex = ih.getColumnIndex("direct"); final int lineNameColumnIndex = ih.getColumnIndex("line_name"); final int snoColumnIndex = ih.getColumnIndex("sno"); final int stationNameColumnIndex = ih.getColumnIndex("station_name"); try { for (Station s : busLines) { ih.prepareForInsert(); ih.bind(directColumnIndex, s.direct); ih.bind(lineNameColumnIndex, s.lineName); ih.bind(snoColumnIndex, s.sno); ih.bind(stationNameColumnIndex, s.stationName); ih.execute(); } db.setTransactionSuccessful(); } finally { ih.close(); db.endTransaction(); db.close(); } |
4、使用SQLiteStatement
查看InsertHelper時(shí),官方文檔提示改類已經(jīng)廢棄,請(qǐng)使用SQLiteStatement
String sql = "insert into bus_line_station(direct,line_name,sno,station_name) values(?,?,?,?)"; SQLiteStatement stat = db.compileStatement(sql); db.beginTransaction(); for (Station line : busLines) { stat.bindLong(1, line.direct); stat.bindString(2, line.lineName); stat.bindLong(3, line.sno); stat.bindString(4, line.stationName); stat.executeInsert(); } db.setTransactionSuccessful(); db.endTransaction(); db.close(); |
下圖是以上4中方法在批量插入1萬條數(shù)據(jù)消耗的時(shí)間
可以發(fā)現(xiàn)第三種方法需要的時(shí)間最短,鑒于該類已經(jīng)在API17中廢棄,所以第四種方法應(yīng)該是最優(yōu)的方法。
posted on 2014-05-23 10:12 順其自然EVO 閱讀(13947) 評(píng)論(0) 編輯 收藏 所屬分類: android