2013-11-26 18 views
0

我正在使用sqlite數據庫,一切都很順利。我在表格中添加了4個條目,然後在我的xib文件中添加了textview。現在我希望這個數據應該從放置在項目捆綁中的sqlite數據庫中獲取。但我沒有得到如何將這個數據庫從包中調用到目錄路徑。請幫我解決這個問題。從包中調用sqlite數據庫

+0

我會建議你使用FMDB:https://github.com/ccgus/fmdb – hukir

回答

1

使用此代碼:

首先調用此方法,將檢查wheter DBFILE存儲在文件目錄或沒有。如果不是,它會將您的文件寫入文檔目錄。

-(void)openDatabase { 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error = nil; 
    NSString *dbPath = [self getDBPath]; 

    BOOL success = [fileManager fileExistsAtPath:dbPath]; 
    if(!success) { 
     NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] 
            stringByAppendingPathComponent:@"databasefilename.sqlite"]; 

     success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath 
             error:&error]; 
     if (!success) 
      NSLog(@"Failed to create writable database file with message '%@'.", 
         [error localizedDescription]); 
    } 
} 

- (NSString *) getDBPath { 
    //Search for standard documents using NSSearchPathForDirectoriesInDomains 
    //First Param = Searching the documents directory 
    //Second Param = Searching the Users directory and not the System 
    //Expand any tildes and identify home directories. 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , 
                  NSUserDomainMask, YES); 
    NSString *documentsDir = [paths objectAtIndex:0]; 
    return [documentsDir stringByAppendingPathComponent:@"databasefilename.sqlite"]; 
} 

然後在AppDelegate中或者任何其它類檢查您希望:

if (sqlite3_open([[self getDBPath] UTF8String], &YOUR_SQLITE3_OBJECT) == SQLITE_OK) { 
    NSLog(@"database opened successfully"); 
}