欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android批量插入數(shù)據(jù)到SQLite數(shù)據(jù)庫(kù)的方法

 更新時(shí)間:2017年03月30日 12:03:57   作者:chaoyu168  
這篇文章主要為大家詳細(xì)介紹了Android批量插入數(shù)據(jù)到SQLite數(shù)據(jù)庫(kù)的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

Android中在sqlite插入數(shù)據(jù)的時(shí)候默認(rèn)一條語(yǔ)句就是一個(gè)事務(wù),因此如果存在上萬(wàn)條數(shù)據(jù)插入的話,那就需要執(zhí)行上萬(wàn)次插入操作,操作速度可想而知。因此在Android中插入數(shù)據(jù)時(shí),使用批量插入的方式可以大大提高插入速度。

有時(shí)需要把一些數(shù)據(jù)內(nèi)置到應(yīng)用中,常用的有以下幾種方式:

1、使用db.execSQL(sql)

這里是把要插入的數(shù)據(jù)拼接成可執(zhí)行的sql語(yǔ)句,然后調(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è)置開(kāi)始事務(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(); 

第三種方法需要的時(shí)間最短,鑒于該類已經(jīng)在API17中廢棄,所以第四種方法應(yīng)該是最優(yōu)的方法。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論