2012-03-30 1 views
1

我可以從我的SQLITE數據庫中讀取數據,但無法更新它。我想知道數據庫是否可寫。更新SQLITE查詢FMDB - 初學者

當我將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; 
} 
+0

這是什麼在控制檯打印? OK - 失敗 - 數據庫問題? – 2012-03-30 11:46:14

+0

它說OK,但是當我在控制檯中鍵入select * SQL時,它沒有更新。 – Illep 2012-03-30 12:02:40

+0

爲什麼使用* stringWithFormat *如果你沒有真的放入任何變量?嘗試文字,如果它不起作用刪除單引號。 – lawicko 2012-03-30 19:04:30

回答

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

不錯的工作...解決了我的問題 – ZeeroCool77 2016-01-15 19:03:08