objective-cinsertfmdbnsinteger

FMDB database and xcode inserting into database


I am trying to insert data into a database but I have it seems like it won't insert integer values, it is inputing strings. the app just crashes.

if I push the button that saves it into the database, with the textfields empty, the methods does insert data into the database, but with 0 values, so the method works.

the method I use is:

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

And this is the method I call from my viewController class

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

Solution

  • Always remember to pass any arguments to SQL query as an object. NSInteger in not an object, so put it in NSNumber object and it will work fine.

    This should work for you:

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