【问题标题】:How to query SQlite with integer param in iOS using FMDB?如何使用 FMDB 在 iOS 中使用整数参数查询 SQlite?
【发布时间】:2016-04-28 02:45:59
【问题描述】:

我正在尝试查询在特定列中有字符串的行。但是,我无法得到想要的结果。

代码:

 [_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=? 时,应用程序在FMDatabse.m 文件中的obj = va_arg(args, id); 处崩溃

我也试过这个:

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

根据整数值查询行的正确方法是什么?

【问题讨论】:

    标签: ios sqlite fmdb


    【解决方案1】:

    executeQuery 期望所有参数都是 Objective-C 对象。但是,notesID 是一个整数,因此不是对象。为了解决这个问题,您需要将 notesID 包装在 NSNumber 对象中,如下所示:

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

    【讨论】:

    • 我按照你的建议试过了,但它仍然说绑定或列索引超出范围。
    • 有没有办法使用执行查询而不使用while循环并执行[result next]?
    【解决方案2】:

    正如Mr.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];
    

    【讨论】:

      猜你喜欢
      • 2013-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 2014-12-28
      • 1970-01-01
      相关资源
      最近更新 更多