[英]How to query SQlite with integer param in iOS using FMDB?
我正在嘗試查詢在特定列中具有字符串的行。 但是,我無法獲得理想的結果。
碼:
[_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
,控制台會說:(此處FMResultsSet
為nil
, notes
為nil
)
DB錯誤1:“%”附近:語法錯誤
我還嘗試通過在=和%d之間留一個空格
當我使用: notesid='%d'
控制台會說:(這里FMResultsSet
不是nil
, notes
是nil
)
DB錯誤25:綁定或列索引超出范圍
當我使用時: notesid='?'
控制台說
DB錯誤25:綁定或列索引超出范圍
當我使用時: notesid=?
該應用程序在obj = va_arg(args, id);
崩潰了obj = va_arg(args, id);
在FMDatabse.m
文件中
我也試過這個:
[_database executeQuery:[NSString stringWithFormat:@"select * from testNotes where notesid='%d'",notesID]];
基於整數值查詢行的正確方法是什么?
executeQuery
期望所有參數都是Objective-C對象。 但是, notesID
是整數,因此不是對象。 為了解決這個問題,您需要將notesID
包裹在NSNumber
對象中,如下所示:
FMResultSet *results = [_database executeQuery:@"select * from testNotes where notesid=?", @(notesID)];
正如Mage先生建議的那樣,我需要將int值包裝在NSNumber中。 而且,我需要添加
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];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.