jroyce
jroyce

Reputation: 2148

Query using FMDB not returning result

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

Upvotes: 0

Views: 1333

Answers (2)

Darren
Darren

Reputation: 10398

First call [rst next]

Also, are you sure your subject_id is a string and not an int?

And finally, have you seen if you can use lastInsertRowID?

I use like this:

int lastRow = [[self getDatabase]lastInsertRowId];

Upvotes: 0

lawicko
lawicko

Reputation: 7344

From the FMDB documentation:

You must always invoke -[FMResultSet next] before attempting to access the values returned in a query, even if you're only expecting one.

Just call the next method on your rst before you call stringForColumnIndex.

Upvotes: 1

Related Questions