ios - 如何将 40000 条记录快速插入 iPad 中的 sqlite 数据库

标签 ios objective-c performance ipad sqlite

我想将从 Web 服务获取的 40000 条记录插入到我的 iPad 应用程序的 sqlite 数据库中。

我写了下面的代码,但是需要20分钟左右,有没有更快的方法?

- (NSArray *)insertPriceSQLWithPrice:(Price *) price
{

SQLiteManager *dbInfo = [SQLiteManager sharedSQLiteManagerWithDataBaseName:@"codefuel_catalogo.sqlite"];


sqlite3 *database;

NSString *querySQL=[self formatStringQueryInsertWithTable:@"prices_list" andObject:price];


if(sqlite3_open([dbInfo.dataBasePath UTF8String], &database) == SQLITE_OK)
{
    sqlite3_stmt * compiledStatement;


    const char *query_stmt = [querySQL UTF8String];

    int result = sqlite3_prepare_v2(database, query_stmt, -1, &compiledStatement, NULL);

    if (result == SQLITE_OK)
    {
        int success = sqlite3_step(compiledStatement);

        NSLog(@"el numero de success es -> %i",success);
        if (success == SQLITE_ERROR)
            NSLog(@"Error al insertar en la base de datps");

    }
    else
        NSLog(@"Error %@ ERROR!!!!",querySQL);

    sqlite3_finalize(compiledStatement);
}

sqlite3_close(database);
return nil;
}

最佳答案

为了加快插入速度,您需要做三件事:

  • sqlite3_open 的调用移到循环之外。目前,循环没有显示,所以我假设它在你的代码片段之外
  • 添加 BEGIN TRANSACTIONCOMMIT TRANSACTION 调用 - 您需要在插入循环之前开始事务并在循环结束后立即结束.
  • 使 formatStringQueryInsertWithTable 真正参数化 - 目前看来您没有充分使用准备好的语句,因为尽管使用了 sqlite3_prepare_v2,但您有在您的代码中没有调用 sqlite3_bind_XYZ

这里是 a nice post that shows you how to do all of the above .它是纯 C 语言,但作为 Objective C 程序的一部分可以正常工作。

char* errorMessage;
sqlite3_exec(mDb, "BEGIN TRANSACTION", NULL, NULL, &errorMessage);
char buffer[] = "INSERT INTO example VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)";
sqlite3_stmt* stmt;
sqlite3_prepare_v2(mDb, buffer, strlen(buffer), &stmt, NULL);
for (unsigned i = 0; i < mVal; i++) {
    std::string id = getID();
    sqlite3_bind_text(stmt, 1, id.c_str(), id.size(), SQLITE_STATIC);
    sqlite3_bind_double(stmt, 2, getDouble());
    sqlite3_bind_double(stmt, 3, getDouble());
    sqlite3_bind_double(stmt, 4, getDouble());
    sqlite3_bind_int(stmt, 5, getInt());
    sqlite3_bind_int(stmt, 6, getInt());
    sqlite3_bind_int(stmt, 7, getInt());
    if (sqlite3_step(stmt) != SQLITE_DONE) {
        printf("Commit Failed!\n");
    }
    sqlite3_reset(stmt);
}
sqlite3_exec(mDb, "COMMIT TRANSACTION", NULL, NULL, &errorMessage);
sqlite3_finalize(stmt);

关于ios - 如何将 40000 条记录快速插入 iPad 中的 sqlite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14631477/

相关文章:

Java:如何制定有效的机会方法

ios - 触摸移动方法中物理体尺寸不随 SKSpriteNode 尺寸变化而变化

ios - AVFoundation:在 CanAddInput 处切换相机失败

ios - 使用 SBJson 为 json 响应赋值

ios - 将第一个 UICollectionViewCell 滚动到 View 中心

objective-c - 检测 macOS 鼠标光标下的颜色

android - Android 中的性能测试用例接口(interface)

ios - 如何修复 "alert functions"

ios - .h 中的静态 const 定义与 .m 中的外部 const 定义

python - 有没有办法通过将 python 列表快速转换为 numpy 矩阵来搜索列表?