android SQLite 批量插入資料慢的解決方案 (正對於不同的android api 版本)

來源:互聯網
上載者:User

標籤:android   style   blog   color   使用   os   io   資料   

      SQLite,是一款輕型的資料庫,被廣泛的運用到很多嵌入式的產品中,因為佔用的資源非常少,二其中的操作方式幾乎和我們接觸的資料庫不多,甚至只有幾百K的他自然會被需求者青睞,下面講一下在這樣的輕型資料庫中怎麼對他進行一些讀寫操作。

  之前做選擇連絡人的時候出現如果一個手機裡連絡人超過2000的話,往資料庫裡面插入會非常耗時,不同的手機儲存的條數不同,這個儲存的數量和手機的記憶體有很大的關係,往往取決於手機記憶體,下面對於資料量大的情況來寫一下sqlite的批量查詢。

  SqLite 摻入資料有幾種

  第一種 :由於InsertHelper 這個類在android api17已經被廢棄了,所以要是基於 之前開發的可以使用

 

InsertHelper ih = new InsertHelper(db, "表名");db.beginTransaction();final int 列1= ih.getColumnIndex("列1");final int 列2 = ih.getColumnIndex("列2");try {for (Station s : busLines) {ih.prepareForInsert();ih.bind(列1, 對應的值);ih.bind(列2, 對應的值);ih.execute();}db.setTransactionSuccessful();} finally {ih.close();db.endTransaction();db.close();}

 

 

第二種 :

  同樣在 SQLiteDatabase 中 

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

 

 

第三種:SQLiteDatabase  db.insert("table_name", null, contentValues) 中也可以批量插入

public void insertData(插入資料){db.beginTransaction(); // 手動設定開始事務for (ContentValues v : list) {db.insert("表名", null, v);}db.setTransactionSuccessful(); // 設定交易處理成功,不設定會自動復原不提交db.endTransaction(); // 處理完成db.close()}

 

   

第四種 :  SQLiteStatement  個人比較喜歡用這種方式,對資料的處理看的很清楚明了

String sql = "insert into表名(對應的列) values(?)";SQLiteStatement stat = db.compileStatement(sql);db.beginTransaction();for (資料集) {  //迴圈所要插入的資料}db.setTransactionSuccessful();db.endTransaction();db.close();

 

 

 

總結: 以上的幾種方式都用到了資料庫中的事務這個東西,sqlite語句在其中只會走一次,其他的就是資料迴圈到資料庫中的對象裡,這樣比以前用對象插入,再用for在外圍迴圈快的不知道多少倍,之前插入2000多條資料300多毫秒,以後對於上萬條資料也是非常之快的。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.