標籤: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多毫秒,以後對於上萬條資料也是非常之快的。