java - 如何在 Sqlite Android 中执行从文件中读取的大量插入查询

标签 java android database sqlite insert

目前我有一个要求,我需要阅读大量的插入查询,大约 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/

相关文章:

sql - 在 SQL 数据库中存储大文本 blob 的选项?

database - 普通形式 - 第二与第三 - 区别只是复合键吗?非平凡的依赖?

java - 有效的 Java 异常处理 - 是否在所有情况下都需要它?

java - 给定排序数组,如果数组 A 包含元素 A[i] 且 A[i] = i (递归和分而治之),则返回索引 i

java - JMockit - JMockit 正在读取模拟响应输入流

android - 有没有办法通过应用程序内的按钮将应用程序最小化到后台?

java - Android Studio 调试器突出显示错误行

java - 使用 spring 将属性直接 Autowiring 到 bean 中?

java - 我需要填写什么才能获取我的位置?就像谷歌的蓝点一样

php - 运行新的 SQL 查询 VS。循环遍历相似的数据集 - 什么更有效率?