2010-12-02 81 views
1

當我要打開連接數據庫時,控制檯顯示:「error opening !: 14」。 我在我的項目的文件夾資源中包含「mybase.sqlite」,並使用FMDB框架。數據庫與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]); } } 
+3

盧卡斯你應該將答案標記爲接受,因爲它回答了你的問題。 – 2012-09-22 16:14:42

+1

@LucasMoreria這仍然沒有被接受?這是一個完美的答案。 – MackieeE 2014-05-02 22:36:31

回答

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];