我正在使用以下代码在我的ios应用中插入超过5000的行。如果我没有使用 sqlite3_close(dbv)行;声明我收到错误无法打开数据库。如果我使用语句 sqlite3_close(dbv)数据插入大约需要10-15分钟。如何在不收到错误的情况下更快地插入记录。
//Will enter only in iOS 8+
Class PHPhotoLibrary_class = NSClassFromString(@"PHPhotoLibrary");
if (PHPhotoLibrary_class)
{
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^
{
//Checks for App Photo Album and creates it if it doesn't exist
PHFetchOptions *fetchOptions = [PHFetchOptions new];
fetchOptions.predicate = [NSPredicate predicateWithFormat:@"title == %@", kAppAlbumName];
PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:fetchOptions];
if (fetchResult.count == 0)
{
//Create Album
PHAssetCollectionChangeRequest *albumRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:kAppAlbumName];
//Add default photos to it
NSMutableArray *photoAssets = [[NSMutableArray alloc] init];
for (UIImage *image in albumDefaultImages)
{
PHAssetChangeRequest *imageRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
[photoAssets addObject:imageRequest.placeholderForCreatedAsset];
}
[albumRequest addAssets:photoAssets];
}
}
completionHandler:^(BOOL success, NSError *error)
{
NSLog(@"Log here...");
}];
}
答案 0 :(得分:1)
除了Begin Transaction和Commit Transaction之外,我尝试打开数据库一次,在整个应用程序期间保持连接打开,并关闭应用程序终止时的连接? sqlite3_key的设计很慢,上面的代码强制你插入的每个记录都有一个打开/关键/关闭进程,这会大大减慢你的操作。
答案 1 :(得分:0)
打开数据库后添加此代码
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