android sqlite 批量插入数据优化代码

SQLiteDatabase db = dh.getWritableDatabase();
db.execSQL("PRAGMA cache_size=12000;");
db.beginTransaction();
try {
for (int i = 0; i < 10000; i++) {
String id = "8aebf7b03e410db4013e43ed2369" + String.format("%04d", i);

String sql = generateSql();

SQLiteStatement sqlListStatment = db.compileStatement(sql);
sqlListStatment.bindString(1, id);
sqlListStatment.bindString(2, "20130426091902-187");
sqlListStatment.executeInsert();
// db.execSQL(sql);
}
db.setTransactionSuccessful();
} catch (android.database.SQLException e) {
e.printStackTrace();
} finally {
db.endTransaction();
db.close();
dh.close();

}

性能优化要点,
1,使用事务
db.beginTransaction();
db.setTransactionSuccessful();
db.endTransaction();
使用事务后1万条数据需要13秒左右插入完成
2,使用SQLiteStatement ,预先编译sql再执行,通过传递参数方式来插入数据
改造成这种方式后1万条数据需要8秒左右插入完成

下面是如果用ormlite的时候的处理方法
关键是TransactionManager.callInTransaction和dao.executeRaw函数加上args
try {
TransactionManager.callInTransaction(em.getConnectionSource(), new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
Dao<?, ?> dao = null;
dao = em.findDao(Task.class);
em.enableCache();
for (int i = 0; i < 10000; i++) {
String id = "8aebf7b03e410db4013e43ed2369" + String.format("%04d", i);
String sql = generateSql();

Log.d("MyTag", sql);
String[] args = new String[] { id, "20130426091902-187" };
dao.executeRaw(sql, args);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
});
} catch (SQLException e) {
e.printStackTrace();
}


从结果来看用Ormlite还是慢了些,一个9378毫秒,一个6613毫秒,如果谁还有大批量操作sqlite数据库优化的相关内容,麻烦给我留言,谢谢
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值