使用db.execSQL或使用statement.bind批量插入SQLite(一次​​100-1000行)(我有20000条记录和7列)

时间:2019-04-02 19:48:59

标签: 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(?, ?, ?, ?, ?, ?,?)";
    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();
    }

2 个答案:

答案 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();
}

其他内容:

  • PRAGMA synchronous = OFF可能更快,但存在风险。
  • 一个标准的批量插入技巧是将表上的所有索引删除,插入数据,然后再重新创建索引。
  • 如果使用外键,则在批量插入期间暂时禁用其强制执行也可能会加快速度。只要记住以后再使用PRAGMA foreign_key_check来查找问题即可。

答案 1 :(得分:0)

您似乎在尝试在首次使用时填充数据库。但是,除了这样做之外,将您的应用程序附带可随时使用的数据库文件放入应用程序的assets/中将是更好,更快和更简单的方法,然后在第一次使用时,仅使用该数据库进行“播种” 。有一些帮助程序库可以帮助您:https://github.com/jgilfelt/android-sqlite-asset-helper