我无法捕获 FMDB 空结果集

Posted

技术标签:

【中文标题】我无法捕获 FMDB 空结果集【英文标题】:I can't trap FMDB empty resultset 【发布时间】:2011-12-14 19:47:04 【问题描述】:

我无法从 FMDB 捕获空结果集。 代码如下。我从数据库打开和关闭以及 NSLog "1" 中获取 NSLog,但在 If 语句中没有一个! 如果我在数据库中有数据很好,但如果数据库为空,我想捕获和编辑结果。

    [self openDatabase];

NSNumberFormatter *nfcurrency = [[NSNumberFormatter alloc]init];
[nfcurrency setNumberStyle:NSNumberFormatterCurrencyStyle];
[nfcurrency setLocale:[NSLocale currentLocale]];

FMResultSet *result = [[self getDatabase]executeQuery:@"SELECT BFNeeded FROM tblBets ORDER BY pk DESC LIMIT 1,1;"];
//FMResultSet *result = [[self getDatabase]executeQuery:@"SELECT BFNeeded FROM tblBets ORDER BY pk DESC LIMIT 1,1;"];
NSLog(@"1");
if (result == NULL) 
    NSLog(@"Last BFNeeded Result = nil");
 else 
    while ([result next]) 
        NSLog(@"HERE");
        NSString *lastBFNeeded = [nfcurrency stringFromNumber:[NSNumber numberWithDouble:[result doubleForColumn:@"BFNeeded"]]];
        NSLog(@"lastBFNeeded=%@",lastBFNeeded);
    


NSLog(@"ClosingDB");
[self closeDatabase];

收到第一个回复后继续:

我无法让 hasAnotherRow 按预期工作。 我有这个代码:

FMResultSet *result = [[self getDatabase]executeQuery:@"SELECT BFNeeded FROM tblBets ORDER BY pk DESC LIMIT 0,1;"];

if (result == nil) 
    NSLog(@"Last BFNeeded Result = nil");

else 
    NSLog(@"has results1: %@", [result hasAnotherRow] ? @"YES" : @"NO");
    while ([result next]) 
        NSLog(@"has results2: %@", [result hasAnotherRow] ? @"YES" : @"NO");
    

对于返回结果的数据库,我得到 result1 NO,result2 YES 所以我假设 hasAnotherRow 必须进入 while ([result next]) 循环。 然而,对于一个空数据库,我得到了 result1 NO,它甚至没有得到 result2!

【问题讨论】:

【参考方案1】:

对于产生 0 行的查询,“结果”永远不会为零。

此外,您不应将对象指针与NULL 进行比较——与nil 进行比较。看到这个问题:NULL vs nil in Objective-C

试试这个:

FMResultSet *result = [[self getDatabase]executeQuery:@"SELECT BFNeeded FROM tblBets ORDER BY pk DESC LIMIT 1,1;"];

NSLog ( @"has results: %@", [result hasAnotherRow] ? @"YES" : @"NO" );

【讨论】:

非常感谢。我不知道 hasAnotherRow。 我无法按预期工作。上面有更多信息。谢谢 您只需要预先调用 [result next] 一次,看看它是否返回 nil。 谢谢,我还是 C 的初学者,但学得很快。我把while循环拿出来,只用了[result next],它现在可以工作了。谢谢【参考方案2】:
NSInteger count;

query=[NSString stringWithFormat:@"select Count(*) from %@  where name = 'brandon' ",dbName];
results = [database executeQuery:query ];
while([results next]) 
    count  = [results intForColumnIndex:0];
    NSLog(@"count:%d",count);

如果没有条目,将设置计数为零

【讨论】:

以上是关于我无法捕获 FMDB 空结果集的主要内容,如果未能解决你的问题,请参考以下文章

对空结果集的非法操作[重复]

执行 [FMDatabaseQueue inDatabase:] 后出现错误,因为周围至少有一个打开的结果集?

Amazon athena 无法读取 S3 Access 日志文件,Athena 选择查询为每一列返回空结果集

如何保存结果集并在 TableView 中显示所有数据

JDBC:空/空结果集?

通过 JDBC 调用 Sybase 存储过程时的空结果集