我正在尝试将数据插入数据库,但我觉得它不会插入整数值,而是输入字符串。该应用程序崩溃。
如果我按下将其保存到数据库中的按钮,文本字段为空,则方法会将数据插入数据库,但是值为0,因此该方法可以正常工作。
我使用的方法是:
-(BOOL) insertIntoDatabase: (NSInteger)day: (NSInteger)month:(NSInteger)year:(NSInteger)hours:(NSInteger)minutes:(NSInteger)salary:(NSString *)extra
{
FMDatabase *dbHandler = [FMDatabase databaseWithPath: [Utility getDatabasePath]];
BOOL success;
@try {
[dbHandler open];
success = [dbHandler executeUpdate:@"INSERT INTO inputs (day, month, year, hours, minutes, salary, extra) VALUES (?,?,?,?,?,?,?);",
day, month, year, hours, minutes, salary, extra];
[dbHandler close];
}
@catch (NSException *exception) {
NSLog(@"error..");
}
@finally {
return success;
}
}
这是我从viewController类调用的方法
-(IBAction)enterToDatabase:(id)sender{
InputClassDatabaseHandler *databaseMethods = [[InputClassDatabaseHandler alloc]init];
BOOL accept;
NSInteger day = [_day.text integerValue];
NSInteger month= [_month.text integerValue];
NSInteger year= [_year.text integerValue];
NSInteger hours= [_hours.text integerValue];
NSInteger minutes= [_minutes.text integerValue];
NSInteger salary= [_salary.text integerValue];
//hardcoded for testing...
NSString *extraWork = @"No";
accept = [databaseMethods insertIntoDatabase:day :month :year :hours :minutes :salary :extraWork ];
}
答案 0 :(得分:1)
始终记住将任何参数传递给SQL查询作为对象。 NSInteger不是一个对象,所以把它放在NSNumber对象中它会正常工作。
这应该适合你:
-(BOOL) insertIntoDatabase: (NSInteger)day: (NSInteger)month:(NSInteger)year:
(NSInteger)hours:(NSInteger)minutes:(NSInteger)salary:(NSString *)extra
{
FMDatabase *dbHandler = [FMDatabase databaseWithPath: [Utility getDatabasePath]];
BOOL success = NO;
if(![db open])
{
NSLog(@"Error");
return NO;
}
[dbHandler beginTransaction];
success = [dbHandler executeUpdate:@"INSERT INTO inputs (day, month, year, hours, minutes, salary, extra) VALUES (?,?,?,?,?,?,?);",
[NSNumber numberWithInt:day], [NSNumber numberWithInt:month],
[NSNumber numberWithInt:year], [NSNumber numberWithInt:hours],
[NSNumber numberWithInt:minutes], [NSNumber numberWithInt:salary],
[NSNumber numberWithInt:extra] ];
[dbHandler commit];
[dbHandler close];
return success;
}