Android 批量插入資料到SQLite資料庫

來源:互聯網
上載者:User

標籤:

  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();

 

 

Android 批量插入資料到SQLite資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.