Android:批量插入,当 InsertHelper 被弃用时 [英] Android: Bulk Insert, when InsertHelper is deprecated

查看:19
本文介绍了Android:批量插入,当 InsertHelper 被弃用时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多答案和教程使用 InsertHelper 来做SQLiteDatabase 中的快速批量插入.
但是 InsertHelper 自 API 17 起已弃用.

There is plenty answers and tutorials using InsertHelper to do fast bulk insert in SQLiteDatabase.
But InsertHelper is deprecated as of API 17.

现在在 Android SQLite 中批量插入大量数据的最快方法是什么?

What is now the fastest method to bulk insert large sets of data in Android SQLite ?

到目前为止,我最担心的是 SQLiteStatement 不是使用起来非常舒服,其中 InsertHelper 具有绑定列和绑定值,这有点微不足道.

So far my greatest concern is that SQLiteStatement is not very comfortable to work with, where InsertHelper had binding columns and binding values, which was kind of trivial.

推荐答案

SQLiteStatement 也有绑定方法,它扩展了 SQLiteProgram.

SQLiteStatement has also binding methods, it extends SQLiteProgram.

只需在事务中运行它:

    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    final SQLiteStatement statement = db.compileStatement(INSERT_QUERY);
    db.beginTransaction();
    try {
        for(MyBean bean : list){
            statement.clearBindings();
            statement.bindString(1, bean.getName());
            // rest of bindings
            statement.execute(); //or executeInsert() if id is needed
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

<小时>

编辑

我在 SQLiteQueryBuilder 中找不到好的解决方案,但是就这么简单:

I can't find nice solution in SQLiteQueryBuilder but it's as simple as:

final static String INSERT_QUERY = createInsert(DbSchema.TABLE_NAME, new String[]{DbSchema.NAME, DbSchema.TITLE, DbSchema.PHONE});

static public String createInsert(final String tableName, final String[] columnNames) {
    if (tableName == null || columnNames == null || columnNames.length == 0) {
        throw new IllegalArgumentException();
    }
    final StringBuilder s = new StringBuilder();
    s.append("INSERT INTO ").append(tableName).append(" (");
    for (String column : columnNames) {
        s.append(column).append(" ,");
    }
    int length = s.length();
    s.delete(length - 2, length);
    s.append(") VALUES( ");
    for (int i = 0; i < columnNames.length; i++) {
        s.append(" ? ,");
    }
    length = s.length();
    s.delete(length - 2, length);
    s.append(")");
    return s.toString();
}

这篇关于Android:批量插入,当 InsertHelper 被弃用时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆