0

I am trying to get the next highest PK in an SQLite database that was not originally set up with auto increment and already has hundreds of records. So I made the below method which seems like it should work, but I am not able to get any results from this. I have several other methods that get data from the database that work and can't figure out what I'm doing wrong and I'm going cross-eyed so thought I'd ask for some help.

- (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];

}

The log shows:

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

The header looks like this:

//  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
4

2 回答 2

1

从 FMDB 文档:

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

只需在调用stringForColumnIndex之前先调用下一个方法。

于 2012-01-26T14:47:46.743 回答
0

第一次调用 [rst next]

另外,你确定你subject_id是一个字符串而不是一个int吗?

最后,你有没有看到你是否可以使用lastInsertRowID

我这样使用:

int lastRow = [[self getDatabase]lastInsertRowId];
于 2012-01-26T14:50:23.997 回答