Sqlite database locked error - iOS - ios

I'm using sqlite to use insert and update the data in table view. I can able to update the data only once, on the next attempt it showing database locked. Even though am closing the database, please help. Below is the code.
-(void)saveUserCredential: (NSString *)email :(NSString *)userName :(NSString *)loginTime :(NSString *)source
{
NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
[dateformate setDateFormat:#"yyyy-MM-dd HH:mm"]; // Date formater
NSString *todayDate = [dateformate stringFromDate:[NSDate date]];
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString * query = #"SELECT * from users";
int rc =sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, NULL);
if(rc == SQLITE_OK)
{
if(sqlite3_step(statement) == SQLITE_ROW)
{
NSString *updateSQL = [NSString stringWithFormat:#"update users set email = '%#', username = '%#', source = '%#', created = '%#' where id = '%d'",email, userName, source, todayDate,1];
const char *update_stmt = [updateSQL UTF8String];
sqlite3_prepare_v2(database, update_stmt, -1, &statement, NULL );
//sqlite3_bind_int(statement, 1, 1);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"successfully updated");
}
else{
NSLog(#"Error while updating. '%s'", sqlite3_errmsg(database));
}
}
else
{
NSString *insertSQL = [NSString stringWithFormat:#"insert into users (email,username,source,created) values('%#','%#','%#','%#')",email,userName,source,todayDate];
NSLog(#"INS SQL: %#", insertSQL);
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"INSERTED");
}
else
{
NSLog(#"NOT INSERTED");
}
NSLog(#"hello ");
}
sqlite3_finalize(statement);
sqlite3_close(database);
}
}
}

You need to call
sqlite3_finalize(statement);
for each successful sqlite_prepare_v2 call. It should be balanced. Also use different sqlite3_stmt for each query.
So your code need to be changed like:
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString * query = #"SELECT * from users";
int rc =sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, NULL);
if(rc == SQLITE_OK)
{
if(sqlite3_step(statement) == SQLITE_ROW)
{
NSString *updateSQL = [NSString stringWithFormat:#"update users set email = '%#', username = '%#', source = '%#', created = '%#' where id = '%d'",email, userName, source, todayDate,1];
const char *update_stmt = [updateSQL UTF8String];
sqlite3_stmt *upStmt;
sqlite3_prepare_v2(database, update_stmt, -1, &upStmt, NULL );
//sqlite3_bind_int(upStmt, 1, 1);
if (sqlite3_step(upStmt) == SQLITE_DONE)
{
NSLog(#"successfully updated");
}
else
{
NSLog(#"Error while updating. '%s'", sqlite3_errmsg(database));
}
sqlite3_finalize(upStmt);
}
else
{
NSString *insertSQL = [NSString stringWithFormat:#"insert into users (email,username,source,created) values('%#','%#','%#','%#')",email,userName,source,todayDate];
NSLog(#"INS SQL: %#", insertSQL);
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_stmt *inStmt;
sqlite3_prepare_v2(database, insert_stmt,-1, &inStmt, NULL);
if (sqlite3_step(inStmt) == SQLITE_DONE)
{
NSLog(#"INSERTED");
}
else
{
NSLog(#"NOT INSERTED");
}
NSLog(#"hello ");
sqlite3_finalize(inStmt);
}
sqlite3_finalize(statement);
sqlite3_close(database);
}
}

Related

What's wrong with my iOS sqlite delete method?

I am making a sqlite for iOS. I have succeeded to save data and present, but not delete.
This is my createTable Method:
- (void) createTable: (NSString *) tableName
withField1: (NSString *) field1
withField2: (NSString *) field2
withField3: (NSString *) field3
withField4: (NSString *) field4{
char *err;
NSString *sql = [NSString stringWithFormat:#"CREATE TABLE IF NOT EXISTS '%#' ('%#' "
"TEXT PRIMARY KEY, '%#' TEXT, '%#' TEXT, '%#' TEXT);", tableName, field1,field2,field3,field4];
if(sqlite3_exec(db,[sql UTF8String], NULL,NULL, &err) != SQLITE_OK) {
sqlite3_close(db);
NSAssert(0, #"Could not create table");
} else {
NSLog(#"table created");
}
}
This is my saveData method:
-(void) saveNewData :(NSString*)nickname :(NSString*)url :(NSString*)uid :(NSString*)pswd{
sqlite3_stmt *statement;
if (sqlite3_open([[self filePath] UTF8String], &db) == SQLITE_OK) {
NSString *sql =[NSString stringWithFormat:#"INSERT INTO accountListDB ('nickname', 'url', 'uid', 'pswd') VALUES ('%#', '%#', '%#', '%#')", nickname, url, uid, pswd];
const char *insert_stmt = [sql UTF8String];
sqlite3_prepare_v2(db, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE) {
NSLog(#"data added");
}else{
NSLog(#"failed to added");
}
sqlite3_finalize(statement);
sqlite3_close(db);
}
}
This is my deleteData method, which is not working:
-(void) deleteData:(NSString*)nickname :(NSString*)url :(NSString*)uid :(NSString*)pswd{
sqlite3_stmt *statement;
if (sqlite3_open([[self filePath] UTF8String], &db) == SQLITE_OK) {
NSString *sql =[NSString stringWithFormat:#"DELETE FROM accountListDB WHERE nickname = %#", nickname];
const char *delete_stmt = [sql UTF8String];
sqlite3_prepare_v2(db, delete_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE) {
NSLog(#"data deleted");
}else{
NSLog(#"failed to delete");
}
sqlite3_finalize(statement);
sqlite3_close(db);
}
}
It returns failed to delete.
I think you need to put single quote between your nickename in the query because if it contain space inside that it will not delete the records. Change your delete statement like this
NSString *sql = [NSString stringWithFormat:#"DELETE FROM accountListDB WHERE nickname = '%#'", nickname];

SQLite not ordering data by date in iOS?

I have a CITIES table in which I store cityname and modifieddate. I update the date of a city by current date/time combination and when I retrieve the city names again , I am ordering the data by DATE in DESCENDING order.Now I have tried the queries on Firefox SQLite Manager and they work fine.However I can't find what going wrong here?.
This is how I retrieve data
//Retrieve data
-(NSMutableArray *)getCities{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &citiesDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT cityname FROM CITIES ORDER BY modifieddate DESC"];
const char *query_stmt = [querySQL UTF8String];
NSMutableArray *resultArray = [[NSMutableArray alloc]init];
if (sqlite3_prepare_v2(citiesDB,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *name = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)];
[resultArray addObject:name];
NSLog(#"Result Array : %#",resultArray);
}
sqlite3_finalize(statement);
sqlite3_close(citiesDB);
return resultArray;
}else{
NSLog(#"No Cities Found");
sqlite3_finalize(statement);
sqlite3_close(citiesDB);
return nil;
}
}
return nil;
}
And this is how I update the dates for city names.
//save our data / Update the date
-(void)viewDataBaseForCity:(NSString *)cityName addedDate:(NSString *)dateAdded{
#try {
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &citiesDB)==SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT COUNT(CITYNAME) FROM CITIES WHERE CITYNAME ='%#'", cityName];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(citiesDB, query_stmt, -1, &statement, NULL)!= SQLITE_OK)
{
NSAssert(0, #"Failed to open database");
NSLog(#"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(citiesDB), sqlite3_errcode(citiesDB));
sqlite3_finalize(statement);
sqlite3_close(citiesDB);
}
else{
if (sqlite3_step(statement)==SQLITE_ROW)
{
int count = sqlite3_column_int(statement, 0);
NSLog(#"Found city count is : %d",count);
if (count==0) {
//insert
NSString *insert_sql = [NSString stringWithFormat:#"INSERT INTO CITIES(cityname,modifieddate)VALUES (\'%#\',\'%#\')",cityName,dateAdded];
const char *insert_stmt = [insert_sql UTF8String];
sqlite3_prepare_v2(citiesDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement)==SQLITE_DONE)
{
NSLog(#"Insert Successfull");
sqlite3_finalize(statement);
sqlite3_close(citiesDB);
}
else{
NSLog(#"Insert Failed"); //I also get database locked error here when tried multiple times.
NSLog(#"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(citiesDB), sqlite3_errcode(citiesDB));
sqlite3_finalize(statement);
sqlite3_close(citiesDB);
}
}else{
//update
NSString *querySQL = [NSString stringWithFormat:#"UPDATE CITIES set modifieddate ='%#' WHERE cityname='%#'", dateAdded, cityName];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(citiesDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
NSLog(#"updated successfully");
}
sqlite3_finalize(statement);
sqlite3_close(citiesDB);
}
}else{
NSLog(#"Not Found");
}
}
}
}
#catch (NSException *exception) {
NSLog(#"SQlite exception : %#",[exception reason]);
}
#finally {
}
}
Now the date is stored as string in following format
-(NSString *)dateForCity{
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"YYYY-MM-dd hh:mm:ss"];
NSString *dateString=[dateFormat stringFromDate:today];
return dateString;
}
Modified update query part.Which update only once and then gives database is locked error on next attempt.
//update
NSString *querySQL = [NSString stringWithFormat:#"UPDATE CITIES set modifieddate ='%#' WHERE cityname='%#'", dateAdded, cityName];
NSLog(#"Update Query : %#",querySQL);
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(citiesDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement)==SQLITE_DONE){
NSLog(#"updated successfully");
sqlite3_finalize(statement);
sqlite3_close(citiesDB);
}else{
NSLog(#"%s Update failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(citiesDB), sqlite3_errcode(citiesDB));
sqlite3_finalize(statement);
sqlite3_close(citiesDB);
}
}
You are preparing the query, but not executing it for your update. Your DB is never getting the updated dates.
Additionally, you should be using arguments instead of putting the values into SQL.

How to prevent duplicate data in SQLite3 in iOS 7?

I am trying to prevent duplicate values in SQlite DB.These are essentially a list of names along with which I am storing date as NSString as well.Now what I want to do is , insert a name only once and if inserted second time I want to update the date for it?So far I am able to insert new record, however not able to update it.What am I missing?
-(NSString *)viewDataBaseForCity:(NSString *)cityName addedDate:(NSString *)dateAdded{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &citiesDB)==SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT cityname FROM CITIES WHERE cityname=%#", cityName];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(citiesDB, query_stmt, -1, &statement, NULL)== SQLITE_OK)
{
//This part is not executed at all
if (sqlite3_step(statement)==SQLITE_ROW)
{
self.tempcityName = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
NSLog(#"Found city name : -%#",self.tempcityName);
return self.tempcityName;
}else{
NSLog(#"Not Found");
return nil;
}
sqlite3_finalize(statement);
sqlite3_close(citiesDB);
}
}
return nil;
}
-(void)checkforupdate:(NSString *)cityName addedDate:(NSString *)dateAdded{
{
if(tempcityName == cityName)
{
NSString *querySQL = [NSString stringWithFormat:#"UPDATE CITIES set id=%# WHERE cityname=%#", dateAdded, cityName];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(citiesDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
NSLog(#"updated successfully");
}
sqlite3_finalize(statement);
sqlite3_close(citiesDB);
}
else
{
[self insertintotable:cityName addedDate:dateAdded];
}
}
}
-(void)insertintotable:(NSString *)cityName addedDate:(NSString *)dateAdded{
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &citiesDB)==SQLITE_OK)
{
NSString *insert_sql = [NSString stringWithFormat:#"INSERT INTO CITIES(cityname,id)VALUES (\"%#\",\"%#\")",cityName,dateAdded];
const char *insert_stmt = [insert_sql UTF8String];
sqlite3_prepare_v2(citiesDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement)==SQLITE_DONE)
{
NSLog(#"Saved");
}
else{
NSLog(#"NOT Saved");
}
sqlite3_finalize(statement);
sqlite3_close(citiesDB);
}
}
}
Now the fields of table are created as below.
- (void)initDatabase{
//Putting in caches
NSString *cacheDir = [NSSearchPathForDirectoriesInDomains
(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
databasePath = [cacheDir
stringByAppendingPathComponent:#"CityList.db"];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:databasePath]==NO) {
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &citiesDB)==SQLITE_OK) {
char *errMsg;
NSString *sql_stmt = #"CREATE TABLE IF NOT EXISTS CITIES (";
sql_stmt = [sql_stmt stringByAppendingString:#"cityname TEXT PRIMARY KEY UNIQUE, "];
sql_stmt = [sql_stmt stringByAppendingString:#"id TEXT)"];
if (sqlite3_exec(citiesDB, [sql_stmt UTF8String], NULL, NULL, &errMsg)!=SQLITE_OK) {
NSLog(#"Failed to create table");
}
else
{
NSLog(#"CITIES table created successfully");
}
sqlite3_close(citiesDB);
}else {
NSLog(#"Failed to open/create database");
}
}
}
The below code will help you to do what you want. First check for the cityname you are entering if it exists in database table then update if not exists just insert into the database table.
#synthesis tempcityName;
-(BOOL)saveCity:(NSString *)cityName addedDate:(NSString *)dateAdded{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &citiesDB)==SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT cityname FROM CITIES WHERE cityname=%#", cityName];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(citiesDB, query_stmt, -1, &statement, NULL)== SQLITE_OK)
{
if (sqlite3_step(statement)==SQLITE_ROW)
{
tempcityName = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
}
else{
[self.insertintotable:cityName];
}
sqlite3_finalize(statement);
}
sqlite3_close(citiesDB);
[self.checkforupdate:cityName];
}
To check the data is eligible to update or not:
-(void)checkforupdate:(NSString *)cityName
{
if(tempcityName == cityName)
{
NSString *querySQL = [NSString stringWithFormat:#"UPDATE CITIES set id=%# WHERE cityname=%#", dateAdded, cityName];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(_beaconDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
NSLog(#"updated successfully");
}
sqlite3_finalize(query_stmt);
sqlite3_close(citiesDB);
}
else
{
[self.insertintotable:cityName];
}
}
If the data is not eligible to update then call to insert in DB table
-(void)insertintotable:(NSString *)cityName
{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &citiesDB)==SQLITE_OK) {
//This inserts same name multiple times.
NSString *insert_sql = [NSString stringWithFormat:#"INSERT INTO CITIES(cityname,id)VALUES (\"%#\",\"%#\")",cityName,dateAdded];
const char *insert_stmt = [insert_sql UTF8String];
sqlite3_prepare_v2(citiesDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement)==SQLITE_DONE)
{
NSLog(#"Saved");
return YES;
}
else{
NSLog(#"NOT Saved");
return NO;
}
sqlite3_finalize(statement);
sqlite3_close(citiesDB);
}
First try to update the date.
If this fails (i.e., if sqlite3_changes says no rows were modified), insert a new row:
execute("UPDATE Cities SET id = ? where cityname = ?", ...);
if (sqlite3_changes(citiesDB) == 0) {
execute("INSERT INTO Cities(cityname, id) VALUES(?,?)", ...);
}
First of all you retrieve all data of name from table using Retrieve Query.
if ([RetriveDat containsObject:#"New Data"])
{
// Update Quert
}
else
{
// Insert Query
}

if (sqlite3_step(statement) == SQLITE_DONE) loop does not execute - iOS

below is my code to update records in database...
-(BOOL) addScoreInDatabase:(classname *)objGames
{
BOOL success;
sqlite3 *database;
const char *dbpath = [self.databasePath UTF8String];
if(sqlite3_open(dbpath, &database) == SQLITE_OK)
{
sqlite3_stmt *statement;
NSData *strJson = [objGames getJSON];
NSString *strContent = [[[[NSString alloc]
initWithData:strJson encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:#"\\" withString:#""]stringByReplacingOccurrencesOfString:#"null" withString:#"\"\""];
NSLog(#"strcom %#",strContent);
NSString *query = [NSString stringWithFormat:#"UPDATE gamescore SET data ='%#' WHERE id = 1",strContent];
NSLog(#"query %#",query);
const char *sqlStatement = [query UTF8String];
if(sqlite3_prepare_v2(database, sqlStatement, -1, & statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_DONE)
{
success = TRUE;
}
else
{
success = FALSE;
}
sqlite3_exec(database, "VACUUM;", 0, 0, nil);
}
sqlite3_finalize(statement);
sqlite3_close(database);
}
return success;
}
and it doesn't go inside if (sqlite3_step(statement) == SQLITE_DONE) loop
and Resulted query is
UPDATE gamescore SET data ='{
"title" : "pacman",
"time" : "55",
"score" : "200",
"level" : "1"
}' WHERE id = 1
and when i execute this query in Sqlite Manager it doesn't update the records instead it shows something like this
Can anybody help me to update my records ?!..Thanks !!
You can use sqlite3_exec() method instead of sqlite3_step().
sqlite3_exec() will execute whatever the query you have given.
Try this out.
enter code
-(BOOL) addScoreInDatabase:(classname *)objGames
{
BOOL success;
sqlite3 *database;
const char *dbpath = [self.databasePath UTF8String];
if(sqlite3_open(dbpath, &database) == SQLITE_OK)
{
sqlite3_stmt *statement;
NSData *strJson = [objGames getJSON];
NSString *strContent = [[[[NSString alloc]
initWithData:strJson encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:#"\\" withString:#""]stringByReplacingOccurrencesOfString:#"null" withString:#"\"\""];
NSLog(#"strcom %#",strContent);
NSString *query = [NSString stringWithFormat:#"UPDATE gamescore SET data ='%#' WHERE id = 1",strContent];
NSLog(#"query %#",query);
const char *sqlStatement = [query UTF8String];
if(sqlite3_prepare_v2(database, sqlStatement, -1, & statement, NULL) == SQLITE_OK)
{
sqlite3_exec(database, "VACUUM;", 0, 0, nil);
}
sqlite3_finalize(statement);
sqlite3_close(database);
}
return success;
}

SQLite iOS Insert data

Im trying to insert just one name to my sqlite file. im using this code but it's not working :/
-(void)InsertRecords:(NSMutableString *) txt{
if(addStmt == nil) {
const char *sql = "INSERT INTO myMovies (movieName) VALUES(?) ";
if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
else
sqlite3_bind_text(addStmt, 1, [txt UTF8String], -1, SQLITE_TRANSIENT);
}
if(SQLITE_DONE != sqlite3_step(addStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
sqlite3_reset(addStmt);
}
pass your query to this method and try,
-(void)Insertdata:(NSString*)query{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:#"YourDBName.sql"];
if(sqlite3_open([databasePath UTF8String],&db) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"%#",query];
char *errmsg=nil;
if(sqlite3_exec(db, [querySQL UTF8String], NULL, NULL, &errmsg)==SQLITE_OK)
{
NSLog(#".. Row Added ..");
}
}
sqlite3_close(db);
}
An "out of memory" error from sqlite typically means the database handle you are using hasn't been opened yet. Make sure you are calling sqlite3_open_v2 with the database variable shown in the code you posted?
ok finally I made it ! this is the code that I used for everyone who need it :
-(void)InsertRecords:(NSMutableString *)txt{
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"movieData.sqlite"];
const char *dbpath = [dbPath UTF8String];
sqlite3 *contactDB;
sqlite3_stmt *statement;
NSLog(#"%#",dbPath);
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO myMovies (movieName) VALUES (\"%#\")", txt];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
sqlite3_bind_text(statement, 1, [txt UTF8String], -1, SQLITE_TRANSIENT);
} else {
NSLog(#"error");
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
}
Try this:
//save our data
- (BOOL) saveEmployee:(Employee *)employee
{
BOOL success = false;
sqlite3_stmt *statement = NULL;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &mySqliteDB) == SQLITE_OK)
{
if (employee.employeeID > 0) {
NSLog(#"Exitsing data, Update Please");
NSString *updateSQL = [NSString stringWithFormat:#"UPDATE EMPLOYEES set name = '%#', department = '%#', age = '%#' WHERE id = ?",
employee.name,
employee.department,
[NSString stringWithFormat:#"%d", employee.age]];
const char *update_stmt = [updateSQL UTF8String];
sqlite3_prepare_v2(mySqliteDB, update_stmt, -1, &statement, NULL );
sqlite3_bind_int(statement, 1, employee.employeeID);
if (sqlite3_step(statement) == SQLITE_DONE)
{
success = true;
}
}
else{
NSLog(#"New data, Insert Please");
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO EMPLOYEES (name, department, age) VALUES (\"%#\", \"%#\", \"%#\")",
employee.name,
employee.department,
[NSString stringWithFormat:#"%d", employee.age]];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(mySqliteDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
success = true;
}
}
sqlite3_finalize(statement);
sqlite3_close(mySqliteDB);
}
return success;
}

Resources