有很多答案和教程使用InsertHelper在SQLiteDatabase中快速批量插入 但是,从API 17开始,InsertHelper已被弃用。
现在什么是在Android SQLite中批量插入大量数据的最快方法?
到目前为止,我最关心的是SQLiteStatement使用起来不太舒服,其中InsertHelper具有绑定列和绑定值,这是微不足道的。
答案 0 :(得分:26)
SQLiteStatement还有绑定方法,它扩展了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找不到好的解决方案,但它很简单:
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();
}
答案 1 :(得分:1)
答案 2 :(得分:1)
我遇到了同样的问题,无法找到SQLiteStatement如何轻松替换DatabaseUtils.InsertHelper,因为您需要手动构建SQL查询。
我最终使用 SQLiteDatabase.insertOrThrow ,可以轻松替换现有代码。我只需要添加一个空列hack来处理我插入空ContentValues的情况。
是的,该语句未编译为稍后重用,但手动构建INSERT查询并绑定所有参数太麻烦了。如果您修改代码,我很想知道大批量插入数据集的影响性能(仅限于不推荐使用InsertHelper)。
答案 3 :(得分:1)
我刚刚对默认类进行了备份,只保留了与InsertHelper相关的代码,请查看this gist。
我很确定不推荐使用它来清理SDK utils类。我的班级剩下的只是使用非弃用的东西。