【问题标题】:Getting unable to open database file while inserting bulk data in sqlite db在 sqlite db 中插入批量数据时无法打开数据库文件
【发布时间】:2015-07-08 11:54:37
【问题描述】:

我正在使用以下代码在我的 ios 应用程序中插入超过 5000 行。如果我没有使用 sqlite3_close(dbv) 行;声明我收到一个错误无法打开数据库。如果我使用语句 sqlite3_close(dbv) 数据插入大约需要 10-15 分钟。我该怎么做才能更快地插入记录而不会出错。

-(void)insertrecordIntoTable:(NSString*)SQLStatement
{
    NSString *sqlStr=SQLStatement;
    const char *sql=[sqlStr UTF8String];
     const char* key = [@"StrongPassword" UTF8String];
    sqlite3_stmt *statement1;
    @try {

        int res = sqlite3_open([[self.databaseURL path] UTF8String], &dbv);
        if (res != SQLITE_OK)
            sqlite3_open([[self.databaseURL path] UTF8String], &dbv);

        sqlite3_key(dbv, key, (int)strlen(key));

        if(sqlite3_prepare_v2(dbv, sql, -1, &statement1, nil)==SQLITE_OK)
        {
            NSLog(@"done");
        }
        else
        {
             NSLog(@"the error occurred here is %s ",sqlite3_errmsg(dbv));
        }

        res =sqlite3_step(statement1);

        if(res !=SQLITE_DONE)
          NSLog(@"Error upadating table");

        sqlite3_finalize(statement1);
        sqlite3_close(dbv);
    }
    @catch (NSException *exception) {

    }
    @finally {
        sql=NULL;
        sqlStr=NULL;
        SQLStatement=NULL;
    }
}

【问题讨论】:

    标签: ios sqlcipher


    【解决方案1】:

    除了 Begin Transaction 和 Commit Transaction 我尝试打开数据库一次,在整个应用程序期间保持连接打开,并在应用程序终止时关闭连接? sqlite3_key 的设计速度很慢,上面的代码强制为您插入的每条记录执行打开/键/关闭过程,这将大大减慢您的操作速度。

    【讨论】:

      【解决方案2】:

      打开数据库后添加此代码

      sqlite3_exec(mDb, "BEGIN TRANSACTION", NULL, NULL, &errorMessage);
      

      并且,在关闭数据库之前添加此代码

      sqlite3_exec(mDb, "COMMIT TRANSACTION", NULL, NULL, &errorMessage);
      

      欲了解更多详情,请查看此链接-

      How to insert 40000 records fast into an sqlite database in an iPad

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-11
        • 2014-08-30
        • 1970-01-01
        • 2011-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-15
        相关资源
        最近更新 更多