使用FMDB查询不返回结果

时间:2012-01-26 07:07:45

标签: sqlite fmdb

我正在尝试在SQLite数据库中获得下一个最高的PK,该数据库最初没有设置自动增量并且已经有数百条记录。所以我制作了下面的方法,看起来应该可行,但我无法从中得到任何结果。我还有其他一些方法可以从数据库中获取有效的数据并且无法弄清楚我做错了什么,而且我会睁大眼睛,以为我会请求一些帮助。

- (NSInteger)getNextSubjectId {

    DrillDownAppAppDelegate *appDelegate = (DrillDownAppAppDelegate *)[[UIApplication sharedApplication] delegate];

    FMDatabase *database = [FMDatabase databaseWithPath:appDelegate.getDBPath];    
    [database open];

    FMResultSet *rst = [database executeQuery:@"select max(subject_id) + 1 AS SUBJECT_ID from SUBJECT"];

    NSLog(@"PRINT FIRST SUBJECT_ID = %@", [rst stringForColumnIndex:0]);

    NSString *nextSubId = [rst stringForColumnIndex:0];
    [database close];

    NSLog(@"NEW SUBJECT_ID = %@", nextSubId);


    NSInteger myInt = [nextSubId intValue];

    return myInt;

    //    [maxSubjectId release];

}

日志显示:

2012-01-25 22:56:29.398引用[6992:f803] PRINT FIRST SUBJECT_ID =(null) (gdb)

标题如下所示:

//  Subject.h
//  DrillDownApp

#import <UIKit/UIKit.h>

@interface Subject : NSObject {
    NSInteger subject_id;
    NSString *category_title;
    NSString *title;
    BOOL isDirty;

}

- (id) initWithPrimaryKey:(NSInteger)pk;
- (void) addSubject;
- (NSInteger)getNextSubjectId;

@property (nonatomic, readwrite) BOOL isDirty;
@property (nonatomic, readonly) NSInteger subject_id;
@property (nonatomic, retain) NSString * title;
@property (nonatomic, retain) NSString * category_title;

@end

2 个答案:

答案 0 :(得分:1)

来自FMDB文档:

  

在尝试访问查询中返回的值之前,您必须始终调用 - [FMResultSet next],即使您只想要一个。

在致电 stringForColumnIndex 之前,只需在 rst 上调用下一步方法。

答案 1 :(得分:0)

首先致电[rst next]

此外,您确定subject_id字符串而不是 int 吗?

最后,你看过你是否可以使用lastInsertRowID

我这样用:

int lastRow = [[self getDatabase]lastInsertRowId];