在sqlite db中插入批量数据时无法打开数据库文件

Getting unable to open database file while inserting bulk data in sqlite db

我正在使用以下代码在我的 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;
    }
}

打开数据库后添加此代码

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

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

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

有关详细信息,请查看此 link-

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

除了开始事务和提交事务之外,我尝试打开数据库一次,在整个应用程序期间保持连接打开,并在应用程序终止时关闭连接? sqlite3_key 设计缓慢,上面的代码强制对您插入的每条记录进行 open/key/close 处理,这将大大降低您的操作速度。