最近在修改项目bug的时候,发现一个数据批量插入数据库的问题。
原来的做法是
public long insertDate(List<CityModel> list) {
synchronized (cityDbHelper) {
long count = 0;
try {
cityDbHelper.open();
ContentValues cv = null;
for (CityModel city : list) {
cv = new ContentValues();
cv.put("cityid", city.CityId);
cv.put("name", city.CityName);
cv.put("pinyin", city.NameSort);
cv.put("hotFlag", city.HotFlag);
count = cityDbHelper.insert(tableName, cv);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cityDbHelper != null) {
cityDbHelper.close();
}
}
return count;
}
}
<pre name="code" class="java">cityDbHelper.insert方法:
public long insert(String table, ContentValues cv) {
long count = 0;
try {
mDb.beginTransaction();
count = mDb.insert(table, null, cv);
mDb.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
mDb.endTransaction();
}
return count;
}
我发现这样插入的话,不仅耗时,而且一直显示加载的dialog都不转了,卡住了,于是在网上查了下关于批量插入的方法,
我参考的是http://www.blogjava.net/qileilove/archive/2014/05/23/414005.html这篇文章
根据这篇文章,我对项目里的方法做了修改
public void insertDate(List<CityModel> list) {
synchronized (cityDbHelper) {
SQLiteDatabase db=cityDbHelper.open().getMDB();
try {
//批量插入
String sql="insert into cityinfo(cityid,name,pinyin,hotFlag) values(?,?,?,?)";
SQLiteStatement stat=db.compileStatement(sql);
db.beginTransaction();
for (CityModel city : list) {
stat.bindString(1, city.CityId);
stat.bindString(2, city.CityName);
stat.bindString(3, city.NameSort);
stat.bindString(4, city.HotFlag);
stat.executeInsert();
}
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
db.endTransaction();
if (cityDbHelper != null) {
cityDbHelper.close();
}
}
}
}
最后发现,不仅插入很快,而且dialog正常转动了。
(笔者第一次发博客,不善言表,请多见谅)