[ios]如何使用 Xcode,读取和写入存在的数据库文件?
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.
我是有点新到 Xcode 和 sqlite。现在我有一个名为"mydb.db"的数据库文件,它已经有一些表和数据。我把它放在我的 mac 文件夹和拖动它到我 Xcode 项目在"支持文件"下。
这里是我的代码,但我发现我可以从这个"mydb.db",只能读取,无法插入数据到它 !当我打开"mydb.db"后执行我由 sqlite 管理器的代码,我找不到的数据,应插入 !
谁能告诉我如何解决这个问题?多谢!
NSString *dbFilePath = [[NSBundle mainBundle] pathForResource:@"mydb" ofType:@"db"];
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:dbFilePath]
[queue inDatabase:^(FMDatabase *db) {
[db executeUpdate:@"INSERT INTO Focus VALUES (?,?,?)" withArgumentsInArray:@[@"100000000",@2,@2]];
}];
解决方法 1:
通过将 sqlite db 文件添加到您的支持文件组在 Xcode 中,只添加的文件到应用程序的包以便在生成过程中它获取与所有其他资源打包。因为应用程序不能写入到其捆绑,你必须 sqlite 数据库从复制文件捆绑到一个可写的位置例如
#define FORCE_RECOPY_DB NO
- (void)copyDatabaseIfNeeded {
NSFileManager *fm = [[NSFileManager alloc] init];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *destinationPath = [documentsPath stringByAppendingPathComponent:@"pte.sqlite"];
void (^copyDb)(void) = ^(void){
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"pte" ofType:@"sqlite"];
NSAssert1(sourcePath, @"source db does not exist at path %@",sourcePath);
NSError *copyError = nil;
if( ![fm copyItemAtPath:sourcePath toPath:destinationPath error:©Error] ) {
DDLogError(@"ERROR | db could not be copied: %@", copyError);
}
};
if( FORCE_RECOPY_DB && [fm fileExistsAtPath:destinationPath] ) {
[fm removeItemAtPath:destinationPath error:NULL];
copyDb();
}
else if( ![fm fileExistsAtPath:destinationPath] ) {
DDLogInfo(@"INFO | db file needs copying");
copyDb();
}
}
现在当您想要打开的数据库,使用中的文件路径的位置。
请注意你就不能来检查您的项目中的 sqlite db 文件和期望找到写入从您的代码的更改。(因为您的代码将现在工作与复制的 sqlite 文件。)
最新最早最热