2013-02-01 47 views
0

我是新開發的iPhone和Mac OS操作系統,請耐心等待。但我努力深入,但找不到解決問題的辦法。我們可以給Xcode的sqlite硬編碼路徑嗎?

我已經通過命令提示符在sqlite中創建了一個數據庫。該數據庫保存在用戶/ DNamto/resources.db

但是,當我嘗試使用下面的代碼片段

// Get the documents directory 
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    docsDir = [dirPaths objectAtIndex:0]; 

    // Build the path to the database file 
    databasePath = [[NSString alloc]initWithString: [docsDir stringByAppendingPathComponent:@"resources.db"]]; 

數據庫將無法打開在我的iPhone應用程序中打開該DB。 該應用程序所搜索的數據庫路徑是: /用戶/ DNamto /庫/應用程序支持/ iPhone模擬器/ 6.0 /應用/ C82C3DAF-4E95-49A7-9A4F-4D69B056DC9D /文檔/ resources.db

燦任何人都可以幫助我獲得正確的數據庫路徑。 我們可以硬編碼數據庫路徑,以便我的應用程序鏈接到它。如果是,請提供代碼片段。

+0

,你必須先在文件夾數據庫的副本,然後你可以打開它 –

+0

感謝吉里什NAD Midhun MP的快速反應。 – DNamto

回答

1

添加您的數據庫應用程序中的&檢查,如果該數據庫存在於文檔目錄或沒有,如果沒有,那麼你需要將它複製的文檔目錄,然後訪問它。 對於cppy下面的代碼在doc目錄使用DB片斷

- (void)copyDatabaseIfNeeded { 

    BOOL success; 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    success = [fileManager fileExistsAtPath:[self getDBPath]]; 
    NSString *databasePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"dbname.sqlite"]; 
    if(success) 
    { 
     return;// remove old one. 
    } 
    [fileManager copyItemAtPath:databasePath toPath:[self getDBPath] error:nil]; 
} 

要打開數據庫使用下面的代碼片段

-(void)openDatabase 
{ 
    @try 
    { 
     [self copyDatabaseIfNeeded]; 
     if(sqlite3_open([[self getDBPath] UTF8String], &mainDatabase)==SQLITE_OK) 
     { 
      NSLog(@"Database opened"); 
     } 
    } 
    @catch (NSException *exception) 
    { 
     NSLog(@"Exception in openDatabase %@ :%@",exception.name,exception.reason); 
    } 
} 

- (NSString *)getDBPath 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
    NSString *documentsDir = [paths objectAtIndex:0]; 
    return [documentsDir stringByAppendingPathComponent:@"dbname.sqlite"]; 
} 

使用下面的代碼片段關閉數據庫。

-(void)closeDatabase:(sqlite3_stmt*)statement 
{ 
    @try 
    { 
     sqlite3_finalize(statement); 
     sqlite3_close(mainDatabase); 
    } 
    @catch (NSException *exception) 
    { 
     NSLog(@"Exception in DatabaseController closeDatabase %@ :%@",exception.name,exception.reason); 
    } 
} 
+0

不要前綴帶'get'的方法。這應該只是'dbPath'或'databasePath'。 – bbum

1

你不能。在實際的設備中,您無法獲得硬編碼路徑。

您需要一個相對路徑。

這裏您的問題是您的數據庫不存在於文檔目錄中。

您需要將數據庫添加到您的主束,並在您需要檢查數據庫是否存在於文件目錄下運行時,如果不是你需要複製它使用NSFileManager.

你可以到文件目錄使用以下代碼將數據庫文件從捆綁包複製到文檔目錄。

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"resource.db"]; 
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:@"resource.db"]; 
NSError *error; 
[[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:folderPath error:&error]; 
相關問題