Updating SQLITE query FMDB - Beginner

2019-07-28 10:26发布

问题:

I could read from my SQLITE DB, but unable to update it. I wonder if the database is writable.

When i copy the SQL to the SQL console the code gets executed successfully. So there's no problem with the SQL.

-(BOOL) updateScores{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"uniques.sqlite"];

    FMDatabase* db = [FMDatabase databaseWithPath:writableDBPath];
    BOOL success;

    if ([db open]) {

        if ([db hadError]) {
            NSLog(@"DB Error %d: %@", [db lastErrorCode], [db lastErrorMessage]);
        } 

        success = [db executeUpdate:[NSString stringWithFormat:@"UPDATE Score SET answer='11' WHERE name LIKE 'jack'"]];

        if (success) {
            NSLog(@"OK");
        }else {
            NSLog(@"FAIL");
        }

        [db close];
    }else {
        NSLog(@"Problem with DB");
    }

    return success; 
}

回答1:

Always pass the arguments to SQL query as an object type, please look at the way arguments are passed to the SQL query. Even if you are passing a number, pass it as

[NSNumber numberWithInt:someValue] 

Try this:

-(BOOL) updateScores
{
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0]; 
  NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"uniques.sqlite"];

  FMDatabase* db = [FMDatabase databaseWithPath:writableDBPath];
  BOOL success = NO;

  if ([db open] != YES) {
        NSLog(@"DB Error %d: %@", [db lastErrorCode], [db lastErrorMessage]);
        return NO; //VERY IMPORTANT
    } 

  [db beginTransaction];
    success = [db executeUpdate:@"UPDATE scores SET answer = ? WHERE name like ?", @"1", @"jack"]; 

    if (success) {
        NSLog(@"OK");
        [db commit];
        [db close];
    }else {
        NSLog(@"FAIL");
    }

   return success; 
}