更新SQLITE查询FMDB - 初学者

时间:2012-03-30 11:21:46

标签: iphone objective-c fmdb

我可以从我的SQLITE数据库中读取,但无法更新它。我想知道数据库是否可写。

当我将SQL复制到SQL控制台时,代码会成功执行。所以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 个答案:

答案 0 :(得分:4)

始终将参数作为对象类型传递给SQL查询,请查看参数传递给SQL查询的方式。即使您传递的是号码,也请将其作为

传递
[NSNumber numberWithInt:someValue] 

试试这个:

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