2012-05-15 61 views
4

從非SQL背景的人,我創建了一個簡單的表格,名爲test,有3個字段:FMDB SQLite的插入失敗

NSString *testtable = @"create table if not exists test(testid integer primary key, userid integer, contentid text)"; 
if (![db executeUpdate:testtable]) { 
    NSLog(@"create test, %d:%@", [db lastErrorCode], [db lastErrorMessage]); 
    return NO; 
} 

當我插入一條記錄表中,我得到一個EXC_BAD_ACCESS錯誤:

if (![db executeUpdate:@"insert into test values(?,?,?)", NULL, 1, @"HELLO"]) { 
    NSLog(@"insert test, %d:%@", [db lastErrorCode], [db lastErrorMessage]); 
    return NO; 
} 

如果我將整列的'userid'類型更改爲文本,這將工作正常。我在控制檯上使用sqlite命令測試這個表,它工作得很好。 你們覺得怎麼樣?謝謝...

我嘗試另一種方式來處理這個問題:

if (![db executeUpdate:@"insert into test values(?,?,?)", NULL, [NSNumber numberWithInt:1], @"HELLO"]) { 
    NSLog(@"testint, %d:%@", [db lastErrorCode], [db lastErrorMessage]); 
    return NO; 
} 

然後它工作。我無法說出原因......也許fmdb只支持對象插入。

+0

只要我們的帶有ErrorCodes的NSLog幫助我解決了我的問題... +1 – CampbellGolf

回答

2

我相信FMDB需要用對象來代替?和int的不是對象。更改1到[NSNumber numberWithInt:1]

此外,你打開你的數據庫你有這樣的事情?

db = [FMDatabase databaseWithPath:writableDBPath]; 

    if ([db open]) { 

添加[db setTraceExecution:TRUE];後立即它會nslog你的SQL文本給你。

可以先創建你的SQL NSString,然後插入你的int,然後讓FMDB運行你已經填充好的字符串。

+0

是的,達倫,你說得對。我仔細閱讀fmdb文檔,找到: 「提供給-executeUpdate:方法(或任何接受va_list作爲參數的變體)的所有參數都必須是對象。以下內容不起作用(並且會導致崩潰)「我嘗試在我的代碼中使用executeUpdateWithFormat,它運行良好。 我通過你的建議添加traceExecution。現在我可以從fmdb獲得更多信息。謝謝! – user1396268

0

executeUpdate:僅支持作爲佔位符值傳遞的對象。 您可以使用executeQueryWithFormat:如果您希望使用printf樣式參數(您可以使用%d來表示您的數字)。就個人而言,我會堅持使用這些對象,因爲executeQueryWithFormat:將最終將值轉換爲對象。

+0

嗨哥斯,感謝你溫暖的心,現在我明白了。 – user1396268