我使用sqlite和fmdb包装器。我的load db代码是:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:@"biscuit.sqlite"];
FMDatabase *db = [FMDatabase databaseWithPath:path];
我将biscuit.sqlite
添加到我的项目中,但此代码创建新文件而不是打开现有文件。如何加载此文件?
答案 0 :(得分:2)
如果您只想从数据库中读取数据,请尝试使用以下代码:
NSString *path = [[NSBundle mainBundle] pathForResource:@"biscuit" ofType:@"sqlite"];
如果您需要读/写访问权限,则必须先将数据库复制到可写用户文件夹。
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"biscuit.sqlite"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if (!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"biscuit.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success) {
NSLog(@"Failed to create writable DB. Error '%@'.", [error localizedDescription]);
} else {
NSLog(@"DB copied.");
}
}else {
NSLog(@"DB exists, no need to copy.");
}