mardi 15 septembre 2015

Update sqlite database Objective-c

I have a sqlite database and i want to make updates . I use this code :

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

but the db is not updated even if "data updated" is logged. But when i get data again from db the same result.

Any ideea when i am wrong ?

Aucun commentaire:

Enregistrer un commentaire