安卓:批量插入,当InsertHelper是德precated [英] Android: Bulk Insert, when InsertHelper is deprecated

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

问题描述

有使用大量的答案和教程<一href="http://developer.android.com/reference/android/database/DatabaseUtils.InsertHelper.html">InsertHelper做快速批量插入在SQLiteDatabase。
但是,<一个href="http://developer.android.com/reference/android/database/DatabaseUtils.InsertHelper.html">InsertHelper是德precated为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 ?

到目前为止,我最关心的是,<一个href="http://developer.android.com/reference/android/database/sqlite/SQLiteStatement.html">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也有结合的方法,它延伸<一个href="http://developer.android.com/reference/android/database/sqlite/SQLiteProgram.html">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();
    }


修改

我找不到<一个很好的解决方案href="https://developer.android.com/reference/android/database/sqlite/SQLiteQueryBuilder.html">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();
}

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

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