Sunday, May 8, 2011

The Right way to do an Update statement in ios

Yesterday i spent a whole hour trying to figure out why Update statement don't work, and then i found the solution,

1-Remember always to finalize your statement after using it (sqlite3_finalize), and closing the database (sqlite3_close), so you won't get this error "database is locked".

2- prepare statement don't execute the statement (sqlite3_prepare_v2), you have to run (sqlite3_step) to actually execute the statement.

3- use update statement as follows :
i want to do something like that
UPDATE users set language = 'en' , rank = 1 WHERE id = 4

and language, rank and id is captured from variables.


sqlite3* database;

if(sqlite3_open([dbpath UTF8String], &database) == SQLITE_OK)
{
NSLog(@"connected to db");
NSString* format =
[NSString stringWithFormat:@"UPDATE Users set language = %@,rank = %d WHERE id = ?", language, rank];

const char* select = [format UTF8String];
sqlite3_stmt* stmt;

int result = sqlite3_prepare_v2(database, select, -1, &stmt,NULL );

if(result == SQLITE_OK)
{
sqlite3_bind_int(stmt, 1, cid);
if(SQLITE_DONE != sqlite3_step(stmt))
{
NSLog(@"Error while updating. '%s'", sqlite3_errmsg(database));
}
sqlite3_finalize(stmt);
}
else
{
NSLog(@"error in statment: %s",sqlite3_errmsg(database));
}
}

sqlite3_close(database);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.