SQLite not ordering data by date in iOS? - 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.

Related

Getting database locked error while adding row 2nd time [duplicate]

This question already has answers here:
sqlite error database is locked
(8 answers)
Closed 6 years ago.
I am getting error Database Locked.
at first attempt it adds the row but after that i am getting the error
database locked.
I am trying to make web page saver so at first time when app loads it is adding the row but when again I try to save any webpage it is not saving and I am getting the error database locked.
Even the deletion is also not happening after saving one web page.
#import "DBManager.h"
static DBManager *sharedInstance = nil;
static sqlite3 *database = nil;
static sqlite3_stmt *statement = nil;
#implementation DBManager
+(DBManager*)getSharedInstance{
if (!sharedInstance) {
sharedInstance = [[super allocWithZone:NULL]init];
[sharedInstance createDB];
}
return sharedInstance;
}
-(BOOL)createDB{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent: #"browser.db"]];
BOOL isSuccess = YES;
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
NSLog(#"insod");
const char *sql_stmt ="create table if not exists list(sno int primary key,name varchar(50),category varchar(30),path varchar(500),fav int)";
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
isSuccess = NO;
NSLog(#"Failed to create table");
}
sqlite3_close(database);
return isSuccess;
}
else {
isSuccess = NO;
NSLog(#"Failed to open/create database");
}
}else{
NSLog(#"File Exist");
}
return isSuccess;
}
-(BOOL) Delete:(NSString *) name{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK){
NSString *query = [NSString stringWithFormat:#"delete from list where name like '%#'",name];
const char *stmt = [query UTF8String];
sqlite3_prepare_v2(database, stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE){
sqlite3_finalize(statement);
return YES;
}else {
NSLog(#"error: %s",sqlite3_errmsg(database));
sqlite3_finalize(statement);
return NO;
}
}else{
sqlite3_close(database);
return NO;
}
}
-(NSDictionary *) CatList:(NSString *) cat{
const char *dbpath = [databasePath UTF8String];
NSDictionary *dict;
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL =[NSString stringWithFormat:#"select name,path from list where category like '%#'",cat];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
// NSLog(#"inside list");
NSMutableArray *arr1 = [[NSMutableArray alloc] init];
NSMutableArray *arr2 = [[NSMutableArray alloc] init];
// NSMutableArray *arr3 = [[NSMutableArray alloc] init];
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSString *name = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
[arr1 addObject:name];
//NSLog(#"%#",name);
NSString *category = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
[arr2 addObject:category];
// //NSLog(#"%#",dept);
// NSString *path = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)];
// [arr3 addObject:path];
}
sqlite3_finalize(statement);
dict = #{#"name":arr1,#"path":arr2};
//NSLog(#"%#",dict);
}else{
NSLog(#"error: %s",sqlite3_errmsg(database));
}
sqlite3_close(database);
}
return dict;
}
- (BOOL) saveData:(NSString*)name category:(NSString*)category path:(NSString*)path{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *highest = #"select max(sno) from list";
const char *Query = [highest UTF8String];
if (sqlite3_prepare_v2(database, Query, -1, &statement, NULL) == SQLITE_OK){
if (sqlite3_step(statement) == SQLITE_ROW){
int sno = sqlite3_column_int(statement, 0);
NSString *insertSQL = [NSString stringWithFormat:#"insert into list values(\"%d\",\"%#\",\"%#\", \"%#\",\"%d\")",sno+1,name, category, path,0];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE){
sqlite3_finalize(statement);
return YES;
}else {
sqlite3_finalize(statement);
return NO;
}
}else{
NSString *insertSQL = [NSString stringWithFormat:#"insert into list values(\"%d\",\"%#\",\"%#\", \"%#\",\"%d\")",1,name, category, path,0];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE){
sqlite3_finalize(statement);
return YES;
}else {
sqlite3_finalize(statement);
return NO;
}
}
}
sqlite3_close(database);
}
return NO;
}
-(BOOL) Fav:(NSString *) name{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK){
NSString *query = [NSString stringWithFormat:#"update list set fav = 1 where name like '%#'",name];
const char *stmt = [query UTF8String];
sqlite3_prepare_v2(database, stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE){
sqlite3_finalize(statement);
return YES;
}else {
sqlite3_finalize(statement);
return NO;
}
}else{
return NO;
}
}
-(NSArray *) GetListFav{
const char *dbpath = [databasePath UTF8String];
NSArray *dict;
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = #"select name from list where fav = 1";
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
NSMutableArray *arr1 = [[NSMutableArray alloc] init];
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSString *name = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 0)];
[arr1 addObject:name];
}
sqlite3_finalize(statement);
dict = arr1;
}else{
NSLog(#"error: %s",sqlite3_errmsg(database));
}
sqlite3_close(database);
}
return dict;
}
-(BOOL) removeFav:(NSString *) name{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK){
NSString *query = [NSString stringWithFormat:#"update list set fav = 0 where name like '%#'",name];
const char *stmt = [query UTF8String];
sqlite3_prepare_v2(database, stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE){
sqlite3_finalize(statement);
return YES;
}else {
sqlite3_finalize(statement);
return NO;
}
}else{
return NO;
}
}
-(NSArray *) GetList{
const char *dbpath = [databasePath UTF8String];
NSArray *dict;
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = #"select name from list";
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
//NSLog(#"inside list");
NSMutableArray *arr1 = [[NSMutableArray alloc] init];
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSString *name = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
[arr1 addObject:name];
}
sqlite3_finalize(statement);
dict = arr1;
}else{
NSLog(#"error: %s",sqlite3_errmsg(database));
}
sqlite3_close(database);
}
return dict;
}
#end
You can only access sqllite once at a time. If you have multiple threads, you can run in this situation. Example:
So always try to close database once it is used using:
sqlite3_close(database);
You need to make sure every sqlite3_open is balanced with a sqlite3_close before trying to do sqlite3_open again:
Your saveData method has quite a few return statements that will prevent the database from ever calling sqlite3_close. Make sure all paths out of the method close the database properly. In the end, this means that you'll try to open the database although it's already open.
Or, better, just open the database once and leave it open, eliminating the repeated opening and closing of the database.
Your Delete, Fav, and removeFav methods are also not closing the database.
A few unrelated observations:
You should be wary about using stringWithFormat to build SQL with string parameters. If the string being searched for had a apostrophe in it, your code will fail. Use ? placeholders and then use sqlite3_bind_text to bind values to those placeholders.
If you make your sno column a AUTOINCREMENT, you won't have to do that "get the max sno before inserting new row" logic. Thus, the CREATE statement might look like:
create table if not exists list (
sno integer primary key autoincrement,
name text,
category text,
path text,
fav integer)
You can then omit sno from the INSERT statements, and it will automatically be assigned a unique identifier.

Memory Issue in sqlite database iOS? [duplicate]

This question already has an answer here:
when to call SQLite cleanup functions?
(1 answer)
Closed 6 years ago.
I have used sqlite database in my app.I am doing CURD operation.I get data from json then i convert that data into arrays after that from arrays i insert the data into sqlite database.In my app when data can be upto more than 1000 records.When database is done then i get memory warning.
I have one function for Inserting data.It firstly check if data exists then update data else insert new record
[[DBManager getSharedInstance]insertData:object];
Function definition -
(BOOL) insertData:(SubComponent *)subcomponent
{
const char *dbpath = [databasePath UTF8String];
if([self getSubComponentDataBySubclientClientInspectionid:subcomponent.componentid : subcomponent.componentsubclientid:subcomponent.componentClientid : subcomponent.componentinspectionid] != nil)
{
[self updateCompSubComponentDataBySubclientId:subcomponent];
return YES;
}
else
{
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
if (sqlite3_exec(database, [#"PRAGMA CACHE_SIZE=500000;" UTF8String], NULL, NULL, NULL) == SQLITE_OK) {
NSLog(#"Successfully changed cache size");
}
else
NSLog(#"Error: failed to set cache size with message %s.", sqlite3_errmsg(database));
NSLog(#"inside isnert query");
NSString *insertSQL = [NSString stringWithFormat:
#"insert into subcomponent(subcomponentid,name,createddate,subclientid,clientid,cliententityid, inspectionid, initialstatus,componentclientname,componentsubclientname, checkedstatus) values (\"%#\",\"%#\",\"%#\",\"%#\",\"%#\",\"%#\",\"%#\",\"%ld\",\"%#\",\"%#\",\"2\")",subcomponent.componentid,subcomponent.componentName,subcomponent.componentcreateddate,subcomponent.componentsubclientid,subcomponent.componentClientid, subcomponent.componentEntityid,subcomponent.componentinspectionid,(long)subcomponent.componentStatus,subcomponent.componentClientName,subcomponent.componentSubclientName];
NSLog(#"%#",insertSQL);
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
sqlite3_finalize(statement);
return YES;
}
else
{
NSLog(#"REMASH DB ERROR %s",sqlite3_errmsg(database));
// sqlite3_reset(statement);
//sqlite3_close(database);
sqlite3_finalize(statement);
return NO;
}
}
sqlite3_close(database);
}
return YES;
}
GET DATA FUNCTION
- (SubComponent*) getSubComponentDataBySubclientClientInspectionid:(NSString*)componentid : (NSString *)subclientid : (NSString *)clientId : (NSString *)inspectionid
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"select * from subcomponent where subcomponentid = \"%#\" and subclientid = \"%#\" and clientid = \"%#\" and inspectionid = \"%#\"",componentid,subclientid, clientId,inspectionid];
NSLog(#"gghgh query is %#",querySQL);
const char *query_stmt = [querySQL UTF8String];
SubComponent *resultArray = [[SubComponent alloc]init];
if (sqlite3_prepare_v2(database,query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *component_id = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)];
resultArray.componentid = component_id;
NSString *name = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 1)];
resultArray.componentName = name;
NSString *createddate = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 2)];
resultArray.componentcreateddate = createddate;
NSString *subclientid = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 3)];
resultArray.componentsubclientid = subclientid;
NSString *clientid = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 4)];
resultArray.componentClientid = clientid;
NSString *entityid = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 5)];
resultArray.componentEntityid = entityid;
NSString *inspectionid = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 6)];
resultArray.componentinspectionid = inspectionid;
NSString *clientName = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 8)];
resultArray.componentClientName = clientName;
NSString *subclientName = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 9)];
resultArray.componentSubclientName = subclientName;
// sqlite3_finalize(statement);
// sqlite3_close(database);
return resultArray;
}
else
{
// sqlite3_finalize(statement);
// sqlite3_close(database);
return nil;
}
}
else
{
NSLog(#"error is %s",sqlite3_errmsg(database));
}
}
// sqlite3_reset(statement);
// sqlite3_finalize(statement);
sqlite3_close(database);
return nil;
}
Update Function
-(void)updateCompSubComponentDataBySubclientId:(SubComponent *)subcomponent
{
NSLog(#"inside update data");
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
if (sqlite3_exec(database, [#"PRAGMA CACHE_SIZE=500000;" UTF8String], NULL, NULL, NULL) == SQLITE_OK) {
NSLog(#"Successfully changed cache size");
}
else
NSLog(#"Error: failed to set cache size with message %s.", sqlite3_errmsg(database));
NSString *querySql=[NSString stringWithFormat:
#"UPDATE subcomponent SET name=\"%#\", createddate=\"%#\", cliententityid =\"%#\",componentclientname=\"%#\", componentsubclientname = \"%#\", checkedstatus = \"2\" where subcomponentid = \"%#\" and subclientid = \"%#\" and clientid = \"%#\" and inspectionid =\"%#\"",subcomponent.componentName,subcomponent.componentcreateddate, subcomponent.componentEntityid,subcomponent.componentClientName,subcomponent.componentSubclientName,subcomponent.componentid, subcomponent.componentsubclientid,subcomponent.componentClientid,subcomponent.componentinspectionid];
const char *sql=[querySql UTF8String];
if(sqlite3_prepare_v2(database,sql, -1, &statement, NULL) == SQLITE_OK)
{
if(SQLITE_DONE != sqlite3_step(statement))
{
NSLog(#"REMASH Error while updating. '%s'", sqlite3_errmsg(database));
}
else
{
//sqlite3_reset(statement);
NSLog(#"Update done successfully!");
}
}
NSLog(#"NOT OK");
sqlite3_finalize(statement);
sqlite3_close(database);
}
}
PS:Can somebody suggest whether use of sqlite_finilaize(),sqlite_close().sqlite_reset() is correct by seeing my code.Because memory is increasing.
This is not a Database issue.
This issue is caused because Application doesn't have a storyboard for the device you are trying to run upon.
XCode no valid compiled storyboard at path

Sqlite database locked error - 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);
}
}

database is locked while inserting data ios

Right now I am inserting into the db on the basis of count. If count is greater than zero than "SELECT" will run and my data will be shown, else "INSERT" will take place. Right now my db is empty so the condition goes to "INSERT" section and in that I am getting "Database is Locked:ERROR". i have gone through some examples and it said like we have to finalize the curent query before starting the new one. I have done that thing too but still my problem is same. Posting my code here :
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
#"SELECT count(*) FROM tables WHERE table_id='%d'",
table_id];
NSLog(#"fetch query is.... %#",querySQL);
const char *query_stmt = [querySQL UTF8String];
sqlite3_stmt *countstmt;
if(sqlite3_prepare_v2(_contactDB, query_stmt, -1, &countstmt, NULL) == SQLITE_OK)
{
NSLog(#"FEtch");
sqlite3_step(countstmt);
rows = sqlite3_column_int(countstmt, 0);
NSLog(#"no of rows is %d",rows);
}
sqlite3_finalize(statement);
}
if(rows>0)
{
NSLog(#"NO of rows is : %d",rows);
//if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
// {
NSString *querySQQL = [NSString stringWithFormat:
#"SELECT * FROM tables WHERE table_id='%d'",
table_id];
NSLog(#"fetch query is.... %#",querySQQL);
const char *query_stmmt = [querySQQL UTF8String];
if (sqlite3_prepare_v2(_contactDB,
query_stmmt, -1, &statement, NULL) == SQLITE_OK)
{
NSLog(#"yes...");
}
while (sqlite3_step(statement) == SQLITE_ROW)
{
//int i=0;
NSLog(#"yesssss...");
// NSInteger count = sqlite3_column_int(statement, 2);
//NSLog(#"Rowcount is %d",(long)count);
table_data= [[NSString alloc]
initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
status= [[NSString alloc]
initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)];
row_id= [[NSString alloc]
initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
table_idd= [[NSString alloc]
initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)];
//searchResults = [NSMutableArray arrayWithObject:namee];
NSString *finalarrayy;
//for(loop=1;loop<=z;loop++)
//{
finalarrayy=[NSString stringWithFormat:#"%#,%#,%#,%#",row_id,table_data,status,table_idd];
[stringArray addObject:table_data];
NSLog(#"Array....is...%#",stringArray);
}
[defaults setObject:stringArray forKey:#"stringarray"];
[defaults synchronize];
//}
sqlite3_finalize(statement);
}
else{
NSLog(#"INsert");
//if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
// {
for(i=mn; i<=o ; i++)
{
for(j=1;j<=19;j++)
{
k=i*j;
NSString *val=[NSString stringWithFormat:#"%d %# %d %# %d",i,#"x",j,#"=",k];
//tab_data.value=val;
[stringArray addObject:val];
NSString *insertSQLL = [NSString stringWithFormat:
#"INSERT INTO tables(table_data,status,table_id) VALUES ('%#', '%#', '%d')",
val,#"NO",table_id];
NSLog(#"sql stm. is ..%#",insertSQLL);
const char *insert_stmtt = [insertSQLL UTF8String];
sqlite3_prepare_v2(_contactDB, insert_stmtt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"yes");
}
else
{
NSLog(#"Error: failed to insert into the database with message '%s'.", sqlite3_errmsg(_contactDB));
}
}
}
// }
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
PLease tell me what is wrong with my code. The code is running for the first time like if nothing is in the database then values are inserting into the db but for the second time if I want to insert something new into the db then its throwing error"database is locked".Actually I am running the same code in viewdidload and on the action of segmentcontrol. For viewdidload it is running fine but in the case of segmentcontrol it is creating error, any idea regarding this. If someone can modify my code I will be very thankful to him/her.
you must always close the sqlite database after using it ... so add this line sqlite3_close(DB); just after sqlite3_finalize(statement);

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
}

Resources