2016-01-21 52 views
0

我想查詢在特定列中有一個字符串的行。但是,我無法獲得理想的結果。如何使用FMDB在iOS中使用整數參數查詢SQlite?

代碼:

[_database open]; 
FMResultSet *results = [_database executeQuery:@"select * from testNotes where notesid=%d",notesID]; 
NSString *notes=[results stringForColumn:@"notes"]; 

if ([_database hadError]) { 
    NSLog(@"DB Error %d: %@", [_database lastErrorCode], [_database lastErrorMessage]); 
} 

[_database close]; 

我檢查使用SQLite瀏覽器的數據。我發送的值是13,數據存在於表中。

當我使用:notesid=%d控制檯說:(這裏FMResultsSetnilnotesnil

DB錯誤1:近 「%」:語法錯誤

我也試過給出在=和%d之間的空間

當我使用:notesid='%d'控制檯說:(這裏FMResultsSet不是nilnotesnil

DB錯誤25:綁定或列索引超出範圍

,當我使用:notesid='?'控制檯說

DB錯誤25:綁定或列索引超出範圍

而當我使用:notesid=?該應用程序

[_database executeQuery:[NSString stringWithFormat:@"select * from testNotes where notesid='%d'",notesID]]; 

什麼是查詢基於整數值的行的正確方法:在obj = va_arg(args, id);FMDatabse.m文件

我也試過,這是崩潰?

回答

1

executeQuery預計所有參數都是Objective-C對象。但是,notesID是一個整數,因此不是一個對象。爲了解決這個問題,你需要在NSNumber對象像這樣的包裝notesID

FMResultSet *results = [_database executeQuery:@"select * from testNotes where notesid=?", @(notesID)]; 
+0

我想如你所說,但它仍然表示綁定或列索引超出範圍。 –

+0

有沒有辦法使用執行查詢,而不使用while循環和做[下一個結果]? –

0

由於Mr.Mage建議,我需要來包裝的NSNumber int值。此外,我需要添加

while([results next]) { 
    notes = [results stringForColumn:@"notes"]; 
} 

沒有此while循環,我無法獲得所需的結果。

現在的工作代碼爲:

[_database open]; 
FMResultSet *results = [_database executeQuery:@"select * from testNotes where notesid= ?",@(notesID)]; 
NSString *notes; 
while([results next]) { 
    notes = [results stringForColumn:@"notes"]; 
} 
if ([_database hadError]) { 
    NSLog(@"DB Error %d: %@", [_database lastErrorCode], [_database lastErrorMessage]); 
} 

[_database close];