標籤:
Android中在sqlite插入資料的時候預設一條語句就是一個事務,因此如果存在上萬條資料插入的話,那就需要執行上萬次插入操作,操作速度可想而知。因此在Android中插入資料時,使用批量插入的方式可以大大提高插入速度。 有時需要把一些資料內建到應用中,常用的有以下2種方式:其一直接拷貝製作好的SQLite資料庫檔案,其二是使用系統提供的
資料庫,然後把資料批量插入。我更傾向於使用第二種方式:使用系統建立的資料庫,然後批量插入資料。批量插入資料也有很多方法,那麼那種方法更快呢,下面通過一個demo比較一下各個方法的插入速度。
1、使用db.execSQL(sql) 這裡是把要插入的資料拼接成可執行檔sql語句,然後調用db.execSQL(sql)方法執行插入。
| public void inertOrUpdateDateBatch(List<String> sqls) {SQLiteDatabase db = getWritableDatabase();db.beginTransaction();try {for (String sql : sqls) {db.execSQL(sql);}// 設定事務標誌為成功,當結束事務時就會提交事務db.setTransactionSuccessful();} catch (Exception e) {e.printStackTrace();} finally {// 結束事務db.endTransaction();db.close();}} |
2、使用db.insert("table_name", null, contentValues) 這裡是把要插入的資料封裝到ContentValues類中,然後調用db.insert()方法執行插入。
| db.beginTransaction(); // 手動設定開始事務for (ContentValues v : list) {db.insert("bus_line_station", null, v);}db.setTransactionSuccessful(); // 設定交易處理成功,不設定會自動復原不提交db.endTransaction(); // 處理完成db.close() |
3、使用InsertHelper類 這個類在API 17中已經被廢棄了
| 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時,官方文檔提示改類已經廢棄,請使用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萬條資料消耗的時間 可以發現第三種方法需要的時間最短,鑒於該類已經在API17中廢棄,所以第四種方法應該是最優的方法。
Android批量插入資料到SQLite資料庫