目前我有一个要求,我需要阅读大量的插入查询,大约 100 000 个查询写在一个 .sql 文件中。我需要从 SdCard 读取这个文件并更新我的应用程序中的本地 sqlite 数据库。
我正在使用以下代码成功更新:
同时我担心性能问题和应用程序挂起的风险,当它像一个更重的 sql 文件的任务时。我需要改变我现在使用的方法吗?是否有更好的 Sqlite 数据库实现来无风险地执行此任务。
/* Iterate through lines (assuming each insert has its own line
and theres no other stuff) */
while (insertReader.ready()) {
String insertStmt = insertReader.readLine();
db.execSQL(insertStmt);
bytesRead += insertStmt.length();
int percent = (int) (bytesRead * 100 / totalBytes);
// To show the updating data progress
if (previousPercent < percent) {
System.out.println(percent);
previousPercent = percent;
Bundle b = new Bundle();
b.putInt(AppConstants.KEY_PROGRESS_PERCENT, percent);
Message msg = new Message();
msg.setData(b);
errorViewhandler.sendMessage(msg);
}
result++;
}
insertReader.close();
最佳答案
我发现将大量数据导入数据库的最快方法是在 ContentProvider 上使用 applyBatch()
.
这是我从我的一个项目中减少的一个例子:
ArrayList<ContentProviderOperation> cpoList = new ArrayList<ContentProviderOperation>();
while (condition) {
ContentProviderOperation.Builder b = ContentProviderOperation.newInsert(YourOwnContentProvider.CONTENT_URI);
b.withYieldAllowed(true);
b.withValue(COLUMN_ONE, 1);
b.withValue(COLUMN_TWO, 2);
cpoList.add(b.build());
// You could check here, whether you have a lot of items in your list already. If you do, you should send them to applyBatch already.
}
if(cpoList.size() > 0) {
context.get().getContentResolver().applyBatch(YourOwnContentProvider.AUTHORITY, cpoList);
}
作为 applyBatch 的示例实现:
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) {
ContentProviderResult[] result = new ContentProviderResult[operations.size()];
int i = 0;
SQLiteDatabase sqlDB = db.getWritableDatabase();
sqlDB.beginTransaction();
try {
for (ContentProviderOperation operation : operations) {
result[i++] = operation.apply(this, result, i);
}
sqlDB.setTransactionSuccessful();
} catch (OperationApplicationException e) {
// Deal with exception
} finally {
sqlDB.endTransaction();
}
return result;
}
关于java - 如何在 Sqlite Android 中执行从文件中读取的大量插入查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36567772/