1

当我要打开与数据库的连接时,控制台说:“错误打开!:14”。我在项目的文件夹资源中包含了“mybase.sqlite”,并且正在使用 FMDB 框架。

对于开放连接,我正在使用以下代码:

 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];    
    FMDatabase* db = [FMDatabase databaseWithPath:@"/mybase.sqlite"];
    if (![db open]) {
        NSLog(@"Não abriu o banco de dados.");
        [pool release];
        return 0;
    }

在 AppDelegate 中,我包含了以下代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
*)launchOptions {    

    // Override point for customization after application launch.  HomeViewController *homeVC = [[HomeViewController alloc] init];  navigationController = [[UINavigationController alloc] initWithRootViewController:homeVC];    [self createEditableCopyOfDatabaseIfNeeded];  [window addSubview:navigationController.view];
    [window makeKeyAndVisible]; 
    return YES; }

- (void)createEditableCopyOfDatabaseIfNeeded{  BOOL success;  NSFileManager
*fileManager = [NSFileManager defaultManager];  NSError *error;  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  NSString
*documentsDirectory = [paths objectAtIndex:0];  NSString
*writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"mybase.sqlite"];  success = [fileManager fileExistsAtPath:writableDBPath];  NSLog(@"Success %d", success);  if (success) return;    NSString
*defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"mybase.sqlite"];  success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];  if (!success) {   NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);  }  }
4

1 回答 1

13

我认为您的开放路径可能不正确。您正在指定一个没有意义的路径,就好像您的数据库文件位于根文件夹中一样。

FMDatabase* db = [FMDatabase databaseWithPath:@"/mybase.sqlite"];

上面应该将此代码用于文件路径,您在问题中已经有了。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"mybase.sqlite"];
FMDatabase* db = [FMDatabase databaseWithPath:writableDBPath];
于 2010-12-02T21:59:04.703 回答