问题描述
有使用大量的答案和教程InsertHelper做快速批量插入在SQLiteDatabase。
但是,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 ?
到目前为止,我最关心的是,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();
}
这篇关于安卓:批量插入,当InsertHelper是德precated的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!