Add table to existing database IOS sqlite [closed] - ios

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am using SQLite DB in my iOS app. In my screen 1, I was successfully able to create a Database, a table, insert into it and retrieve from it.
However from screen 2 when I am trying to create a table in the same database and insert values, I am unable to.
This is the code which I am using.
-(void) 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:
#"coning.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: _databasePath ] == NO)
{
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS order (ID INTEGER PRIMARY KEY AUTOINCREMENT , NAME TEXT UNIQUE , ADDRESS TEXT UNIQUE, PHONE TEXT UNIQUE)";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create table");
}
sqlite3_close(_contactDB);
} else {
NSLog(#"Failed to open/create database");
}
}
}
- (void)saveData {
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT OR REPLACE INTO order (name, address, phone) VALUES (\"%#\", \"%#\", \"%#\")",
#"name", #"address", #"phone"];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_contactDB, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"added");
} else {
NSLog(#"Failed to add contact");
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}
I have been using the same code to add entries in table 1 but when I do the same to create table 2, its says 'Failed to add contact'. Can someone suggest where I might be going wrong?
Also I want to make the PK of table 1 as a FK in table 2.

You can use sqlite3_exec() method instead of sqlite3_step().
sqlite3_exec() will execute whatever the query you have given.
I am sure, It will definitely help you.
-(BOOL)createNewTableInExistingDb
{
NSArray *array=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath=[array objectAtIndex:0];
filePath =[filePath stringByAppendingPathComponent:#"database.db"];
NSFileManager *manager=[NSFileManager defaultManager];
BOOL success = NO;
if ([manager fileExistsAtPath:filePath])
{
success =YES;
}
if (!success)
{
NSString *path2=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"database.db"];
success =[manager copyItemAtPath:path2 toPath:filePath error:nil];
}
createStmt = nil;
NSString *tableName=#"SecondTable";
if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
if (createStmt == nil) {
NSString *query=[NSString stringWithFormat:#"create table %#(RegNo integer, name text)",tableName];
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &createStmt, NULL) != SQLITE_OK) {
return NO;
}
sqlite3_exec(database, [query UTF8String], NULL, NULL, NULL);
return YES;
}
}
return YES;
}

Related

Can not read data from the sqlite in iOS

I checked from sqlitebrowser that I successfully created sqlite and inserted data to sqlite, but now my problem is I could not read data from sqlite. I am new to sqlite.
Should I open the sqlite first, and read it? Where is wrong on my code below?
This code for open the existing sqlite.
-(void)openSqlite{
NSString *docsDir = [NSString stringWithFormat:#"Questiondata.db"];
NSArray *dirPaths;
_databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:#"Questiondata.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:_databasePath] == NO) {
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK) {
char *errorMessage;
const char *sql_statement ="CREATE TABLE IF NOT EXISTS users (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
if (sqlite3_exec(_contactDB,sql_statement,NULL,NULL,&errorMessage) != SQLITE_OK) {
NSLog(#"Failed to create the table");
}
sqlite3_close(_contactDB);
}
else{
NSLog(#"Fail to open/create the table");
}
}
}
This is code for read data from existing sqlite.
-(void)readData{
NSLog(#"we came here");
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB)) {
NSString *querySQL = [NSString stringWithFormat:#"SELECT * FROM Questions WHERE QuestionNumber = 1"];
const char*query_statement = [querySQL UTF8String];
if (sqlite3_prepare_v2(_contactDB, query_statement, -1, &statement, NULL)== SQLITE_OK) {
if (sqlite3_step(statement) == SQLITE_ROW) {
NSString *addressfield = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement,0)];
NSLog(#"finddata:%#",addressfield);
}else{
NSLog(#"notfinddatabase");
}
sqlite3_finalize(statement);
}else{
NSLog(#"failed to serache database");
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
NSLog(#"not be here");
}
}
In openSqlite method
const char *sql_statement ="CREATE TABLE IF NOT EXISTS users (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
and in your query
NSString *querySQL = [NSString stringWithFormat:#"SELECT * FROM Questions WHERE QuestionNumber = 1"];
table name and column name are not same.
Change in Place "Questions" with "users" .
and also change "QuestionNumber" with the table column.
May be, it will helps you or feel free.
sqlite doesn't report all errors until you start accessing the data. For example just about any filename and path will pass without errors.
First of all you must check that, the database is in the Documents folder?
It's not there by default.
Perhaps it's in the main bundle?
Try this:
NSString *dbName = [[NSBundle mainBundle] pathForResource:#"dbFile" ofType:#"db"];

How to retrieve data from sqlite manager [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I created database and also created table in that by using sqlite manager(mozilla).Now i want to retrieve that data into my iOS application.How can i do with programatically. Can you please any one help me how to do that. Thank you.
Use something like this:
import:
#import "sqlite3.h"
CHECK IF DB EXISTS:
NSString *docsDir;
NSArray *dirPaths;
NSString *databasePath;
sqlite3 *DB;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"YourDbName.sqlite"]]; //put your db name here
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &DB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS YourTable (Value INTEGER PRIMARY KEY, column TEXT)";
if (sqlite3_exec(DB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
}
sqlite3_close(DB);
}
}
Get DB Values:
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &DB) == SQLITE_OK) //News is a sqlite variable initialized like this: sqlite3* News;
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT * FROM YourDBName"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(DB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSString* example; //example variable to assign data from db
example = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)]; //change the 0 to 1,2,3.... for every column of your db
}
sqlite3_finalize(statement);
}
sqlite3_close(DB);
}
To retrieve that data into your iOS application.follow following steps
lets consider your SQlite DB have name YourDB which have table information and columns Name, Place and City and DatabasePath is your path where you store your SQlite DB
const char *dbpath = [DatabasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &YourDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
#"SELECT Place, City FROM students WHERE Name=Bob"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(YourDB,query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *Place = [[NSString alloc]
initWithUTF8String:
(const char *) sqlite3_column_text(
statement, 0)];
NSString *City = [[NSString alloc]
initWithUTF8String:(const char *)
sqlite3_column_text(statement, 1)];
}
sqlite3_finalize(statement);
}
sqlite3_close(YourDB);
}
Put that "sqlite" file in App's bundle and then you can use that file.

Data not inserting into sqlite database

Hi in my application I have data which want insert into my sqlite database .So I have already created the database successfully, But the problem its not insert data into database.
My database creation code.
- (void)createDatabase
{
NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *doctumentsDirectory = [directories lastObject];
self.databasePath = [[NSString alloc] initWithString:[doctumentsDirectory stringByAppendingPathComponent:#"/bp.sqlite"]];
NSFileManager *fileManager = [NSFileManager defaultManager];
// create DB if it does not already exists
if (![fileManager fileExistsAtPath:self.databasePath]) {
const char *dbPath = [self.databasePath UTF8String];
if (sqlite3_open(dbPath, &_myDataBase) == SQLITE_OK) {
char *errorMsg;
const char *sql_statement = "CREATE TABLE IF NOT EXISTS br (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, COST TEXT,QUTY TEXT)";
if (sqlite3_exec(_myDataBase, sql_statement, NULL, NULL, &errorMsg) != SQLITE_OK) {
[self errorCreatingTable:[NSString stringWithFormat:#"failed creating table. ERROR:%s", errorMsg]];
}
sqlite3_close(_myDataBase);
} else {
[self errorCreatingTable:#"failed openning / creating table"];
}
}
}
My insert code i have UIButton action method where i give my insert code.
-(void)aMethod2:(UIButton*)sender
{
NSString *inr=[intarr objectAtIndex:sender.tag];
NSLog(#"%#",inr);
NSString *item=[self.menuarray objectAtIndex:sender.tag];
NSLog(#"%#",item);
NSString *cost=[self.menuarray1 objectAtIndex:sender.tag];
NSLog(#"%#",cost);
NSString *sql = [NSString stringWithFormat:#"INSERT INTO br ('NAME','COST','QUTY') VALUES ('%#','%#','%#')",item,cost,inr];
NSLog(#"%#",sql);
}
I have used the above code where get the data and inserting into my database but values all passing correctly problem is its not inserting into my database please tell me how to resolve this issue I have been stuck here for long time help me out.
Thanks.
When i saw your question, i couldn't help seeing something that was a bit strange to me... and that was seeing my own code. thanks for using my code snippet from stackoverflow :) getting error while trying to create sqlite database 'Could not create table' IOS7
Any way, here is a quick example on how to insert:
- (void)insertDictionaryToDataBase:(NSDictionary *)dictionary
{
if (dictionary) {
sqlite3_stmt *sql_statement;
const char *dbPath = [self.databasePath UTF8String];
if (sqlite3_open(dbPath, &_inboxDatabase) == SQLITE_OK) {
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO MY_TABLE_NAME (COLUMN_A, COLUMN_B, COLUMN_C) VALUES (?,?,?)"];
const char *insertStatement = [insertSQL UTF8String];
sqlite3_prepare_v2(_inboxDatabase, insertStatement, -1, &sql_statement, NULL);
sqlite3_bind_text(sql_statement, 1, [dictionary[#"key1"] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(sql_statement, 2, [dictionary[#"key2"] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_int(sql_statement, 3, [dictionary[#"key3"] intValue]);
if (sqlite3_step(sql_statement) == SQLITE_DONE) {
NSLog(#"sucess!");
}
sqlite3_finalize(sql_statement);
sqlite3_close(_inboxDatabase);
}
}
}
DBmanager.h file
#import <Foundation/Foundation.h>
#import <sqlite3.h>
#interface DBReadWriteUtil : NSObject
+(sqlite3*)copyDbToDocumentsDirectoryIfNotExist;
+(BOOL)insertData:(NSString*)arg1 cost:(int)arg2 quty:(int)arg3;
+(NSDictionary*)getUploadPendingMedia;
+(int)removeMediaPOStFormId:(int)row_id;
#end
DBmanager.m file
#import "DBReadWriteUtil.h"
#implementation DBReadWriteUtil
+(sqlite3*)copyDbToDocumentsDirectoryIfNotExist{
NSString *dbPath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"bp.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:dbPath]) {
NSString *localDB = [[NSBundle mainBundle] pathForResource:#"bp" ofType:#"sqlite"];
NSError *err;
if(![fileManager copyItemAtPath:localDB toPath:dbPath error:&err]){
if (DEBUG_MODE) {
NSLog(#"SQL: Not ABLE TO COPY FILE -> %#",err);
}
}
}
sqlite3 *db_connction;
if(sqlite3_open([dbPath UTF8String], &db_connction) != SQLITE_OK){
if (DEBUG_MODE) {
NSLog(#"SQL : Not ABLE TO CONNECT DB:");
}
}
return db_connction;
}
+(BOOL)insertData:(NSString*)arg1 cost:(int)arg2 quty:(int)arg3{
BOOL dbStatus = NO;
sqlite3 *db_connction = [DBReadWriteUtil copyDbToDocumentsDirectoryIfNotExist];
sqlite3_stmt *compiledStmt;
const char *query = "insert into br(NAME,cost,quay) values(?,?,?)";
if(sqlite3_prepare_v2(db_connction, query, -1, &compiledStmt, NULL) == SQLITE_OK ){
sqlite3_bind_text(compiledStmt,1,[arg1 UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_int(compiledStmt, 2, arg2);
sqlite3_bind_int(compiledStmt,3, arg3,-1);
NSUInteger err = sqlite3_step(compiledStmt);
if (err != SQLITE_DONE){
if(DEBUG_MODE){
NSLog(#"error while Inserting image %d %s",err, sqlite3_errmsg(db_connction));
}
}else{
dbStatus = YES;
}
}
sqlite3_finalize(compiledStmt);
sqlite3_close(db_connction);
return dbStatus;
}
Call DBmanager
BOOL successDB = [DBReadWriteUtil insertData: arg1 cost:arg2 quty:arg3];
try this code...
-(void)Insertdata:(NSString*)query{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:#"bp.sqlite"];
NSLog(#"%#",databasePath);
if(sqlite3_open([databasePath UTF8String],&_myDataBase) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"%#",query];
char *errmsg=nil;
if(sqlite3_exec(_myDataBase, [querySQL UTF8String], NULL, NULL, &errmsg)==SQLITE_OK)
{
NSLog(#".. Inserted ..");
}
}
sqlite3_close(_myDataBase);
}

Communication of the database

I am working with the communication of sqlite database from one viewcontroller to another, but some how i am not getting the database on the second view controller. Bellow is the code which i am using for it.:-
On First View controller
//Creating a table of MOtivational Thoughts
dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPath objectAtIndex:0];
Second.databasePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"S.H.E.D_DB"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([ filemgr fileExistsAtPath: Second.databasePath] == NO) {
const char *dbpath = [Second.databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS THOUGHTS (ID integer ,Motivation_Thaought TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create table");
}
else
{
NSLog(#" created table");
}
sqlite3_close(contactDB);
} else {
}
}
// Fetching Data from table of MOtivational Thoughts
if(sqlite3_open([Second.databasePath UTF8String], &contactDB) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
int randomNumber = [self getRandomNumberBetween:0 to:6];
NSString *queryString = [NSString stringWithFormat:#"Select * FROM THOUGHTS where ID= '%d'",randomNumber];
const char* sql = [queryString UTF8String];
NSLog(#"path value : %#", Second.databasePath);
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(contactDB, sql, -1, &compiledStatement, nil)==SQLITE_OK) {
// Loop through the results and add them to the feeds array
NSLog(#"Ready to enter while loop");
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSLog(#"reading");
NSString *aid = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
motivationView.text = aid;
NSLog(#"Thought of the day %#", aid);
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(contactDB);
// Do any additional setup after loading the view from its nib.
}
On Second View Controller
NSLog(#"path value : %#", databasePath);
if(sqlite3_open([databasePath UTF8String], &contactDB) == SQLITE_OK){
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS SHEDSLIST (SHED_ID integer ,SHED_Name TEXT ,SHED_Description TEXT, SHED_TIME DATETIME)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create table");
}
else
{
NSLog(#" created table");
}
sqlite3_close(contactDB);
} else {
}
PLease locate my error and give me sutable solution.
May be you should access the database path as self.databasePath in SecondViewController because I believe you have created a property for that. Instead of that you are trying to access some instance variable databasePath. Look at your following code in FirstViewController:
Second.databasePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"S.H.E.D_DB"]];

SQLite3 not updating in iOS application

I have a table called Budgets that stores its settings, values, and a purchases nsarray full of the object purchases.
I am not sure what I am doing wrong in my method right here, but it will not update the database on an existing entry. It saves a new budget just fine.
- (BOOL) saveBudget:(Budget *)budget
{
BOOL success = false;
sqlite3_stmt *statement = NULL;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
if (budget.budgetID > 0) {
NSLog(#"Existing data, Update Please");
NSString *updateSQL = [NSString stringWithFormat:#"UPDATE BUDGETS set name = '%#', budget = '%#', customdate = '%d', customday = '%d', rolloverp = '%d', rollovern = '%d', purchases = ?8 WHERE id = ?", budget.name, budget.budget, budget.customDate, budget.customDay, budget.rolloverP, budget.rolloverN];
const char *update_stmt = [updateSQL UTF8String];
sqlite3_prepare_v2(database, update_stmt, -1, &statement, NULL);
sqlite3_bind_int(statement, 1, budget.budgetID);
sqlite3_bind_blob(statement, 8, [budget.purchases bytes], [budget.purchases length], SQLITE_TRANSIENT);
if (sqlite3_step(statement) == SQLITE_DONE)
{
success = true;
}
}
else
{
NSLog(#"New data, Insert Please");
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO BUDGETS (name, budget, customdate, customday, rolloverp, rollovern, purchases) VALUES (\"%#\", \"%#\", \"%d\", \"%d\", \"%d\", \"%d\", ?8)", budget.name, budget.budget, budget.customDate, budget.customDay, budget.rolloverP, budget.rolloverN];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt, -1, &statement, NULL);
sqlite3_bind_blob(statement, 8, [budget.purchases bytes], [budget.purchases length], SQLITE_TRANSIENT);
if (sqlite3_step(statement) == SQLITE_DONE)
{
success = true;
}
}
sqlite3_finalize(statement);
sqlite3_close(database);
NSLog(#"Save Success");
}
return success;
}
I am assuming that the query is incorrect, but I may be wrong.
EDIT:
Here is how I am adding the database. Again, new entries are added and retrieved from the database just fine. Old entries are retrieved but will not update.
- (void) initDatabase
{
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent:#"budget.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if([filemgr fileExistsAtPath:databasePath] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString sql_stmt = #"CREATE TABLE IF NOT EXISTS BUDGETS (";
sql_stmt = [sql_stmt stringByAppendingString:#"id INTEGER PRIMARY KEY AUTOINCREMENT, "];
sql_stmt = [sql_stmt stringByAppendingString:#"name TEXT, "];
sql_stmt = [sql_stmt stringByAppendingString:#"budget DOUBLE, "];
sql_stmt = [sql_stmt stringByAppendingString:#"customdate INTEGER, "];
sql_stmt = [sql_stmt stringByAppendingString:#"customday INTEGER, "];
sql_stmt = [sql_stmt stringByAppendingString:#"rolloverp INTEGER, "];
sql_stmt = [sql_stmt stringByAppendingString:#"rollovern INTEGER, "];
sql_stmt = [sql_stmt stringByAppendingString:#"purchases BLOB)"];
if (sqlite3_exec(database, [sql_stmt UTF8String], NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create table BUDGETS");
}
else
{
NSLog(#"BUDGETS table created successfully");
}
sqlite3_close(database);
}
else
{
NSLog(#"Failed to open/create database");
}
}
}
ANOTHER QUESTION:
I also have a question on whether I am saving the purchases NSArray correctly or not. I assumed that this would work.
Make sure the Location your pointing to the SQlite data base is right.And before executing the query make sure the table is in open state and ready to the operation. Refer this code:
sqlite3_stmt *statement;
sqlite3 *cPDB;
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Data base path
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"cPDB.db"]];
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &cPDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"UPDATE USER_SESSION_INFO SET \"%#\" = \"%#\", synState = 'false' WHERE sessionName=\"%#\"",categoryTy,state,sessionName];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(cPDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if((sqlite3_step(statement)) != SQLITE_DONE)
NSLog(#"Not Updated");
else
{
NSLog(#"Succesfully updated row !");
return YES;
}
}
}
Found the problem. There were no single quotes around ?8 in the update statement. Well, its always the small problems. Thanks everyone!

Resources