Mar*_*era 18 sqlite android bulkinsert android-contentprovider android-sqlite
有很多答案和教程使用InsertHelper在SQLiteDatabase中快速批量插入.
但是从API 17开始,不推荐使用InsertHelper.
什么是在Android SQLite中批量插入大量数据的最快方法?
到目前为止,我最关心的是SQLiteStatement使用起来不太舒服,其中InsertHelper具有绑定列和绑定值,这有点微不足道.
paw*_*eba 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();
}
Run Code Online (Sandbox Code Playgroud)
编辑
我在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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9436 次 |
| 最近记录: |