2013-04-22 114 views
1

我是新的SQLITE數據庫,我正在使用FMDB。在我的應用程序中,我想插入一些數據到數據庫中。我用下面的代碼來插入數據。FMDB插入查詢執行但沒有在數據庫中插入數據

-(void)insertBookmark 
{ 

    NSString *bundlePath = [[NSBundle mainBundle] bundlePath]; 
    NSString *dbFilePath = [bundlePath stringByAppendingPathComponent:@"ISGData.sqlite"]; 
    FMDatabase *database = [FMDatabase databaseWithPath:dbFilePath]; 
    [database open]; 
    [database executeUpdate:@"INSERT INTO bookmark (pageno) VALUES (?);",page, nil]; 
    NSLog(@"%@",[database lastErrorMessage]); 
    [database close]; 

} 

這裏的「bookmark」是我的數據庫中表名稱爲「pageno」的整型實體的名稱。雖然我在查詢應用程序崩潰中傳遞一個int值,顯示訪問不正確。如果我傳遞一個字符串值,在我的日誌中,我得到了「沒有錯誤」,但值沒有被插入到數據庫中。我的代碼中有任何錯誤嗎?

回答

4

您正試圖修改應用程序包內的數據庫。該包本身是隻讀的。爲此,您必須先將數據庫文件複製到文檔目錄,然後打開&對其進行修改。

總之,隨着替換第一個三線在你的函數:

FMDatabase *database = [self openDatabase]; 

隨着openDatabase就像這個答案定義:how do we open an already existing database fmdb and where to include it?

+0

ok我明白了。非常感謝你.... – 2013-04-22 07:48:38

0

Hampus是正確的。您需要將其複製到文檔目錄中以執行寫入操作:

BOOL success; 
NSError *error; 

NSFileManager *fileManager = [NSFileManager defaultManager]; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *filePath = [documentsDirectory stringByAppendingString:@"ISGData.sqlite"]; 

success = [fileManager fileExistsAtPath:filePath]; 
if (success) return; 

NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:@"ISGData.sqlite"]; 
success = [fileManager copyItemAtPath:path toPath:filePath error:&error]; 

if (!success) { 
    NSAssert1(0, @"Failed to copy DB. Error %@", [error localizedDescription]); 
} 
+0

好吧,我會試試這個。非常感謝你。 – 2013-04-22 07:50:23