需要向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(?, ?, ?, ?, ?, ?,?)";
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();
}
答案 0 :(得分:0)
您一次只能插入一行。因此,从您的代码中删除怪异的东西,并结合我在注释中提到的有关仅绑定一次常量的内容(免责声明:这将在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();
}
其他内容:
答案 1 :(得分:0)
您似乎在尝试在首次使用时填充数据库。但是,除了这样做之外,将您的应用程序附带可随时使用的数据库文件放入应用程序的assets/
中将是更好,更快和更简单的方法,然后在第一次使用时,仅使用该数据库进行“播种” 。有一些帮助程序库可以帮助您:https://github.com/jgilfelt/android-sqlite-asset-helper