如何在iPad中快速插入40000个logging到sqlite数据库

我想插入40000条logging,我从一个Web服务到我的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的调用sqlite3_open循环之外。 目前,循环没有显示,所以我认为它是在你的代码片段之外
  • 添加BEGIN TRANSACTIONCOMMIT TRANSACTION调用 – 您需要在插入循环之前开始事务并在循环结束后立即结束。
  • 使formatStringQueryInsertWithTable真正参数化 – 目前看来,您并没有使用准备好的语句,因为尽pipe使用了sqlite3_prepare_v2 ,但在代码中没有调用sqlite3_bind_XYZ

这里是一个很好的post,告诉你如何做到上述所有 。 这是简单的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); 

对于我来说,调用BEGIN TRANSACTION然后加载大约20个插入,然后调用COMMIT TRANSACTION给了18倍的性能增加 – 很棒的提示! caching准备好的语句没有什么帮助。