Android 使用db.execSQL或使用statement.bind(我有20000条记录和7列)大容量插入SQLite(一次100-1000行)
需要一次至少向SQLite 100-500条记录插入批量数据…有7列,每行有7个值 使用statment.bind 如果出现问题,请建议使用db.execSQL批插入来实现Android 使用db.execSQL或使用statement.bind(我有20000条记录和7列)大容量插入SQLite(一次100-1000行),android,sqlite,bulkinsert,query-performance,Android,Sqlite,Bulkinsert,Query Performance,需要一次至少向SQLite 100-500条记录插入批量数据…有7列,每行有7个值 使用statment.bind 如果出现问题,请建议使用db.execSQL批插入来实现 SQLiteDatabase db = DBHelper.getWritableDatabase(); String str = "INSERT INTO DBAdapter.KEY_BD1_DB_NAME(a, b, c, d, e, f,g) VALUES(?, ?, ?, ?, ?, ?,?)";
SQLiteDatabase db = DBHelper.getWritableDatabase();
String str = "INSERT INTO DBAdapter.KEY_BD1_DB_NAME(a, b, c, d, e, f,g) VALUES(?, ?, ?, ?, ?, ?,?)";
SQLiteStatement statement = db.compileStatement(str);
db.beginTransactionNonExclusive();
try {
for (int i=0;i<arraylist.length;i++)
{
statement.bindLong(1, id);
statement.bindLong(2, alist[i]);
statement.bindLong(3, blist[i]);
statement.bindString(4, strTStamp[0]);
statement.bindString(5, strTStamp[1]);
statement.bindLong(6, j);
statement.bindLong(7, tstamp);
if (alist.size>100)
{
if(count==100)
{
statement.executeInsert();
statement.clearBindings();
count=0;
}
else
{
count++;
}
}
}
statement.executeInsert();
statement.clearBindings();
db.setTransactionSuccessful();
Log.d("INSERT","Done");
return true;
} catch (SQLException ex) {
Log.w("SqlErr", "At kkr : " + ex.toString());
return false;
}finally {
db.endTransaction();
db.close();
}
一次只能插入一行。所以,从你的代码中去掉一些奇怪的东西,并加入我在一篇关于只绑定常量值的评论中提到的一点免责声明:这在C中可以工作;对于java/android绑定不是100%确定,插入一组数据的标准方法应该如下所示:
SQLiteDatabase db = DBHelper.getWritableDatabase();
db.beginTransaction();
try {
String str = "INSERT INTO DBAdapter.KEY_BD1_DB_NAME(a, b, c, d, e, f,g) VALUES(?, ?, ?, ?, ?, ?,?)";
SQLiteStatement statement = db.compileStatement(str);
statement.bindLong(1, id);
statement.bindString(4, strTStamp[0]);
statement.bindString(5, strTStamp[1]);
statement.bindLong(6, j);
statement.bindLong(7, tstamp);
for (int i=0;i<arraylist.length;i++) {
statement.bindLong(2, alist[i]);
statement.bindLong(3, blist[i]);
statement.executeInsert();
}
db.setTransactionSuccessful();
Log.d("INSERT","Done");
return true;
} catch (SQLException ex) {
Log.w("SqlErr", "At kkr : " + ex.toString());
return false;
} finally {
db.endTransaction();
db.close();
}
其他材料:
可能更快,但也有风险。
标准的批量插入技巧是删除表上的任何索引,插入数据,然后重新创建索引。
如果使用外键,在大容量插入期间暂时禁用它们的强制可能也会加快速度。只需记住,以后再查找问题。
看起来您正试图在首次使用时填充数据库。但与其这样做,不如在应用程序的资产中附带现成的数据库文件,然后在首次使用时使用该数据库作为种子,这样做会更好、更快、更简单。有一些帮助程序库可以帮助您做到这一点:您的代码有问题吗?它起作用了吗?问题是什么?请具体说明您遇到了什么问题,您尝试了什么,等等。上面提到的代码将对批量插入进行性能调整???…将数据插入数据库需要时间……hv一次至少插入100行需要多少时间?多少时间是可以接受的?你的逻辑看起来很好,除了那些计数的东西。准备一个insert语句,启动一个事务,每次在循环中使用新的值绑定重新使用该准备好的语句,直到完成,提交。没有比这更神奇的方法了——这已经是更好的方法了。我唯一能建议的是跳过clearBindings调用,只绑定不会随每行更改的值一次,而不是在循环中重复执行。大约80-90秒非常感谢Shawn