2015-09-15 59 views
0

我有一个sqlite数据库,我想进行更新。我使用此代码:更新sqlite数据库Objective-c

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 

path = [documentsDirectory stringByAppendingPathComponent:@"memo.sqlite"]; 
const char *sqlStatement = "CREATE TABLE IF NOT EXISTS NOTES (title text PRIMARY KEY, category TEXT,content TEXT , dataAdd TEXT,deadline TEXT,place TEXT,photos TEXT);"; 

char *error; 

// path = [[NSBundle mainBundle] pathForResource:@"memo" ofType:@"sqlite"]; 

if (sqlite3_open([path UTF8String], &contactDB) == SQLITE_OK) 
{ 
    NSLog(@"DB is open"); 
    if(sqlite3_exec(contactDB, sqlStatement, NULL, NULL, &error) == SQLITE_OK) 
    { 
     NSLog(@"All tables are created");  
    } 
} 
else 
{ 
    NSLog(@"DB can't be open"); 
} 

querySQL1 = @"select category from notes where id=8"; 
const char * query_stmt = [querySQL1 UTF8String]; 

sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL); 

NSString *updateSQL = [NSString stringWithFormat: 
         @"UPDATE notes set title=\"%@\" , content=\"%@\" WHERE title LIKE '\"%@\"'",self.titleNote.text,self.contentNote.text,self.titleNote.text]; 

const char *insert_stmt = [updateSQL UTF8String]; 
sqlite3_stmt *updateStmt = nil; 

if(sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL) == SQLITE_OK) 
{ 

    if (sqlite3_step(statement) == SQLITE_DONE) 
    { 
     NSLog(@"data updated"); 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Your notes was updated." 
                 message:@"" 
                 delegate:self 
               cancelButtonTitle:@"OK" 
               otherButtonTitles:nil]; 
     [alert show]; 
     sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL); 
     char* errmsg; 
     sqlite3_exec(contactDB, "COMMIT", NULL, NULL, &errmsg); 

     if(SQLITE_DONE != sqlite3_step(updateStmt)){ 
      NSLog(@"Error while updating. %s", sqlite3_errmsg(contactDB)); 
     } 
    } 
    else{ 
     NSLog(@"Error while creating update statement. '%s'", sqlite3_errmsg(contactDB)); 
    } 
} 
else 
{ 
    NSLog(@"Error while creating update statement. '%s'", sqlite3_errmsg(contactDB)); 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error to delete note." 
                message:@"" 
                delegate:self 
              cancelButtonTitle:@"Cancel" 
              otherButtonTitles:nil]; 
    [alert show]; 
} 

但即使记录“数据更新”,数据库也不会更新。但是当我从数据库重新获得数据相同的结果。

任何ideea当我错了?

+0

这段代码基本上是不可读的。请按顺序获取您的语句变量。 –

回答

0

我认为sqlite3_step()返回SQLITE_DONE只是表示没有错误(即您的语句在语法上是正确的),而不是行被更新。

您必须使用sqlite3_changes()来确定更新的行数。