我想获得最初没有设置自动增量并且已经有数百条记录的SQLite数据库中的下一个最高PK。所以我做了下面的方法,似乎它应该工作,但我无法从这得到任何结果。我还有其他几种从数据库中获取数据的方法,但无法弄清楚我做错了什么,并且我会全神贯注,所以我想请求一些帮助。使用FMDB查询不返回结果
- (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 =(空) (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
非常感谢,修复它。我知道这简直是愚蠢的。由于初始化问题,我之前将它作为NSString使用,但是现在已经修复,所以它直接转换为NSInteger,而不必转换它。我正在检查如何使用lastInsertRowId,但我的主键字段最初并未设置为自动增量,并且不确定这是否可行。 – jroyce
很高兴你的工作。最简单的疏忽总是让我们绊倒。 – Darren