简体   繁体   中英

Updating SQLITE query FMDB - Beginner

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM