[英]How to query SQlite with integer param in iOS using FMDB?
I am trying to query a row which has a string in a particular column. 我正在尝试查询在特定列中具有字符串的行。 However, I am unable to get the desired result.
但是,我无法获得理想的结果。
Code: 码:
[_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];
I checked the data using sqlite browser. 我使用sqlite浏览器检查了数据。 The value I'm sending is 13, and the data exists in the table.
我要发送的值为13,并且表中存在数据。
When I use: notesid=%d
the console says: (Here FMResultsSet
is nil
, notes
is nil
) 当我使用:
notesid=%d
,控制台会说:(此处FMResultsSet
为nil
, notes
为nil
)
DB Error 1: near "%": syntax error
DB错误1:“%”附近:语法错误
I also tried by giving a space in between = and %d 我还尝试通过在=和%d之间留一个空格
When I use: notesid='%d'
the console says:(Here FMResultsSet
is not nil
, notes
is nil
) 当我使用:
notesid='%d'
控制台会说:(这里FMResultsSet
不是nil
, notes
是nil
)
DB Error 25: bind or column index out of range
DB错误25:绑定或列索引超出范围
And When I use: notesid='?'
当我使用时:
notesid='?'
the console says 控制台说
DB Error 25: bind or column index out of range
DB错误25:绑定或列索引超出范围
And when I use: notesid=?
当我使用时:
notesid=?
the app is crashed at the obj = va_arg(args, id);
该应用程序在
obj = va_arg(args, id);
崩溃了obj = va_arg(args, id);
in FMDatabse.m
file 在
FMDatabse.m
文件中
I also tried this: 我也试过这个:
[_database executeQuery:[NSString stringWithFormat:@"select * from testNotes where notesid='%d'",notesID]];
What is the proper way to query a row based on integer value ? 基于整数值查询行的正确方法是什么?
executeQuery
expects all arguments to be Objective-C objects. executeQuery
期望所有参数都是Objective-C对象。 However, notesID
is an integer and thus not an object. 但是,
notesID
是整数,因此不是对象。 In order to fix this, you'll need to wrap notesID
in an NSNumber
object like this: 为了解决这个问题,您需要将
notesID
包裹在NSNumber
对象中,如下所示:
FMResultSet *results = [_database executeQuery:@"select * from testNotes where notesid=?", @(notesID)];
As Mr.Mage suggests, I need to wrap the int value in NSNumber. 正如Mage先生建议的那样,我需要将int值包装在NSNumber中。 And also , I need to add
而且,我需要添加
while([results next]) {
notes = [results stringForColumn:@"notes"];
}
Without this while loop, I couldnt get the required result. 没有这个while循环,我将无法获得所需的结果。
Now the working code will be: 现在,工作代码将为:
[_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.