how to update the sqlite database in ios - ios

I am new to ios app development.This is the code for update the sqlite database i am using but its not updating it shows data base is locked.Any help.
-(BOOL) updateSignalCode:(NSString*)deviceString buttonType:(NSString*)name
{
const char *dbPath=[databasePath UTF8String];
if (sqlite3_open(dbPath, &database)==SQLITE_OK) {
NSLog(#"database Opened");
sqlite3_busy_timeout(database, 800);
NSString *insertSQL = [NSString stringWithFormat:#"update deviceDetail Set deviceId = '%#' where buttontype = '%#'",deviceString,name];
const char *insert_stmt = [insertSQL UTF8String];
if (sqlite3_prepare_v2(database, insert_stmt, -1, &statement, NULL)==SQLITE_OK) {
NSLog(#"Query Executed");
if (sqlite3_step(statement) == SQLITE_DONE) {
NSLog(#"Database Updated");
}
else {
NSLog(#"Error while updating.%d %s",sqlite3_errcode(database), sqlite3_errmsg(database));
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return nil;
}

You need to copy your sqlite file to document directory in appdelegate .
- (void)createCopyOfDatabaseIfNeeded {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSLog(#"%#",[self getDBPath]);
success = [fileManager fileExistsAtPath:[self getDBPath]];
if (success){
return;
}
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"db.sqlite"];// replace name of sqlite here
success = [fileManager copyItemAtPath:defaultDBPath toPath:[self getDBPath] error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
-(NSString *)getDBPath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *dbPath = [docsPath stringByAppendingPathComponent:#"db.sqlite"]; // replace name of sqlite here
return dbPath;
}
In Appdelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self createCopyOfDatabaseIfNeeded];
return YES;
}

Related

Read data from existing sqlite.db is working on simulator but not actual device (Objective C)

I don't know how to fix this error, I go to "Build Phases" and add sqlit.db file to Bundle resources but it still error.
Have anyone solve the problem this thing?.
Click Here to see code
-(void) initDatabase{
dbName = #"MBox_karaoke.db";
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writeableDBPath = [documentsDirectory stringByAppendingPathComponent:dbName];
success = [fileManager fileExistsAtPath:writeableDBPath];
if(success){
return;
}
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writeableDBPath error:&error];
if (!success) {
// NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
NSLog(#"Database created failed, %#",[error localizedDescription]);
}
else {
NSLog(#"Database created successfully");
}
}
As an error states resource file not found.
Make sure you copied the database file in bundle. When you drag database to project navigator, make sure that you have checked "Copy item if needed".
Following solution working for me.
-(void)initializeDatabase {
NSError *error;
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [docPaths objectAtIndex:0];
NSString *docPath = [docDir stringByAppendingPathComponent:#"Test.sqlite"];
NSString *template_path = [[NSBundle mainBundle] pathForResource:#"Test" ofType:#"sqlite"];
if (![fm fileExistsAtPath:docPath])
[fm copyItemAtPath:template_path toPath:docPath error:&error];
//-====
}
Your code is correct but some time database file doesn't select target membership that your database doesn't copy your path that it's this type error occur.
First Remove/Uninstall your install app.
Please, Select your database file in xcode and see your target membership is check or uncheck. Uncheck that select check. (See below image)
Run the project simulator and check your database available in your path. Database available that see your database browse contain is correct.
NSLog("Path: %#",defaultDBPath);
My answer
+ (NSString *)databasePath
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *sql_Path=[paths objectAtIndex:0];
NSString *dbPath=[sql_Path stringByAppendingPathComponent:#"MBox_karaoke.sqlite"];
NSFileManager *fileMgr=[NSFileManager defaultManager];
BOOL success;
NSError *error;
success=[fileMgr fileExistsAtPath:dbPath];
if (!success)
{
NSString *path=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:#"MBox_karaoke.sqlite"];
success=[fileMgr copyItemAtPath:path toPath:dbPath error:&error];
}
return dbPath;
}
Create Table and here My Table Name is Account
+ (void) createTableForAccount
{
char *error;
NSString *filePath =[self databasePath];
if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
{
NSString *strQuery=[NSString stringWithFormat:#"CREATE TABLE IF NOT EXISTS Account(id TEXT,name TEXT);"];
sqlite3_exec(database, [strQuery UTF8String], NULL, NULL, &error);
}
else
{
NSAssert(0, #"Table failed to create");
NSLog(#"Account Table Not Created");
}
sqlite3_close(database);
}
Insert Data
+ (void)insertAccountDetails:(NSString *)id:(NSString *)name
{
NSString *dbPath=[self databasePath];
if(sqlite3_open([dbPath UTF8String],&database)==SQLITE_OK)
{
NSString *strQuery = [NSString stringWithFormat:#"INSERT into Account(id,name) values(?,?);"];
if(sqlite3_prepare_v2(database,[strQuery UTF8String] , -1, &stment, NULL)==SQLITE_OK)
{
sqlite3_bind_text(stment, 1, [[self checkEmpty:id] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stment, 2, [[self checkEmpty:name] UTF8String] , -1, SQLITE_TRANSIENT);
sqlite3_step(stment);
sqlite3_reset(stment);
}
sqlite3_finalize(stment);
}
sqlite3_close(database);
}
Fetch or Get Data from Table
+ (void)getAccountDetails
{
NSString *dbPath = [self databasePath];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *query = [NSString stringWithFormat:#"SELECT id,name from Account"];
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &stment, nil) == SQLITE_OK)
{
while (sqlite3_step(stment) == SQLITE_ROW)
{
NSString *idString = [[self charToString: (char *)sqlite3_column_text(stment, 0)]base64DecodedString];
NSString *nameString = [[self charToString: (char *)sqlite3_column_text(stment, 1)]base64DecodedString];
NSMutableArray *arrayId = [[NSMutableArray alloc]init];
NSMutableArray *arrayName = [[NSMutableArray alloc]init];
[arrayId addObject:idString];
[arrayName addObject:nameString];
}
sqlite3_reset(stment);
}
sqlite3_finalize(stment);
}
sqlite3_close(database);
}
Other Methods which called inside the db insert and fetch
insert
+ (NSString *)checkEmpty:(NSString *)check
{
if([check isEqual:[NSNull null]])
check = #" ";
return check;
}
Fetch method
+ (NSString*)charToString:(const char*)chart
{
NSString *string = #" ";
if(string)
{
chart = [self checkEmptyChar:chart];
string=[NSString stringWithUTF8String:chart];
}
return string;
}
+ (const char *)checkEmptyChar:(const char *)check
{
NSString *string = #" ";
if (check == NULL)
check = [string UTF8String];
return check;
}

how to import my.sqlite3 into my iPhone project in Xcode

I drag locationsWOW.sqlite3 file into my project and trying to load it in.The console did't show info about NSLog(#"failed to open database!"); but show NSLog(#"database open");
And even when I change the name of locationsWOW to be locations (#"locations" ofType:#"sqlite3"];)
which is not existing ,still the project successfully compiled and my .sqlite database didn't work.Any could help me a beginner.
Here is my code.
-(id)init{
if (self = [super init]) {
NSString *sqlite3DB = [[NSBundle mainBundle]pathForResource:#"locationsWOW" ofType:#"sqlite3"];
if (sqlite3_open([sqlite3DB UTF8String], &_database) != SQLITE_OK) {
NSLog(#"failed to open database!");
}
}
NSLog(#"database open");
return self;
}
As a beginer just do the following steps in your code
+(NSString *)databasePath
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *sql_Path=[paths objectAtIndex:0];
NSString *dbPath=[sql_Path stringByAppendingPathComponent:#"locationsWOW.sqlite"];
NSFileManager *fileMgr=[NSFileManager defaultManager];
BOOL success;
NSError *error;
success=[fileMgr fileExistsAtPath:dbPath];
if (!success) {
NSString *path=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:#"locationsWOW.sqlite"];
success=[fileMgr copyItemAtPath:path toPath:dbPath error:&error];
}
return dbPath;
}
After when create the Table
+(void)createTable
{
char *error;
NSString *filePath =[self databasePath];
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
{
NSString *strQuery=[NSString stringWithFormat:#"CREATE TABLE IF NOT EXISTS TableName(id TEXT,name TEXT);"];
sqlite3_exec(database, [strQuery UTF8String], NULL, NULL, &error);
}
else
{
NSAssert(0, #"Table failed to create");
NSLog(#"TableName Table Not Created");
}
sqlite3_close(database);
}

SQLite db not writable

I have a pre-populated SQLite db created with the Firefox SQLite Manager plugin.
I have included the DB to my project, added to the target and copied into destination group's folder. Then I created this function to copy the DB in the Documents folder:
-(void) createEditableDatabase{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *writableDB = [[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:#"DB.sqlite"];
success = [fileManager fileExistsAtPath:writableDB];
if (success){
return;
}
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"DB.sqlite"];
error = nil;
success = [fileManager copyItemAtPath:defaultPath toPath:writableDB error:&error];
if (!success){
NSAssert1(0, #"Failed to create writable database file:%#", [error localizedDescription]);
}
if (error){
NSLog(#"error = %#", [error localizedDescription]);
}
}
then I call this function in -(void)viewDidLoad and if I check in the simulator folder, a copy of the DB appears once I start the app.
The app runs fine, I can populate a UICollectionView with the data retrieved from the DB.
Then, when I try to insert some data, I receive no error but no data is added to the DB.
This is the code I use in MyViewController.h :
#property (nonatomic) NSString *DBPath;
#property (nonatomic) sqlite3 *myAppSQLITE;
This is the code I use in MyViewController.m :
-(IBAction)done:(id)sender{
DBPath = [[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:#"DB.sqlite"];
const char *dbpath = [DBPath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &myAppSQLITE) == SQLITE_OK){
NSString *querySQL = [NSString stringWithFormat:#"INSERT INTO myTable (name, age) VALUES('frank',30);"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(myAppSQLITE, query_stmt, -1, &statement, NULL) == SQLITE_OK){
sqlite3_finalize(statement);
}
sqlite3_close(myAppSQLITE);
}
}
I receive no error/warning but the data is never updated, even with a [self.collectionView reloadData];. If I run the same query with SQLite Manager in Firefox, everything works fine. If i open the DB inside the Simulator Documents folder with SQLite Manager, the DB is intact with no updated data. I have the same result running the app with my iPad.
How can I solve this?
Thank you in advance.
P.S: David's suggestion is right, this is a better way to create an editable DB:
- (void) createEditableDatabase{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"DB.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success){
return;
}
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"DB.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
P.S2: this could be an appropriate error checking, let me know if it's right or not.
int rc;
while ((rc = sqlite3_step(statement)) == SQLITE_ROW){
NSLog(#"ROW");
}
if (rc != SQLITE_DONE){
NSLog(#"%s: step error: %d: %s", __FUNCTION__, rc, sqlite3_errmsg(myAppSQLite));
}
You never actually execute the query by calling sqlite3_step.
You want:
if (sqlite3_prepare_v2(myAppSQLITE, query_stmt, -1, &statement, NULL) == SQLITE_OK){
sqlite3_step(statement); // add appropriate error checking
sqlite3_finalize(statement);
}

Create Sqlite database in iOS

I am unable to create sqlite database in my documents directory.
Here is the code:
NSString *fileDir;
NSArray *dirPaths;
//Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDemoApplicationDirectory, NSUserDomainMask, YES);
fileDir = [dirPaths objectAtIndex:0];
// Build the database path
databasePath = [[NSString alloc]initWithString:[fileDir stringByAppendingPathComponent:#"student.sql"]];
NSFileManager *fileMgr = [NSFileManager defaultManager];
if([fileMgr fileExistsAtPath:databasePath] == NO)
{
const char *dbPath = [databasePath UTF8String];
if (sqlite3_open(dbPath, &database) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS(ID INTEGER PRIMARY KEY , NAME TEXT, ADDRESS TEXT, MOBILE INTEGER)";
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) {
_status.text = #"Failed to create table";
}
sqlite3_close(database);
}
else
{
_status.text = #"Failed to open/create database";
}
}
I have debug the code and found that the compiler is not going under this condition.
sqlite3_open(dbPath, &database) == SQLITE_OK
I don't know what i am doing wrong.
Any help will be appreciated...
Thanks,
Check you code to get dirPath, you are getting right path or not, I used following way in my code and its working for me :
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// dirPaths = NSSearchPathForDirectoriesInDomains(NSDemoApplicationDirectory, NSUserDomainMask,YES);
fileDir = dirPaths[0];
// Build the database path
databasePath = [[NSString alloc]initWithString:[fileDir stringByAppendingPathComponent:#"student.sqlite"]];
this is how i managed it.
DataBaseAccess.m
static sqlite3 *database=nil;
-(id)init
{
if(self=[super init])
{
self.user_data=#"user_data.db";
}
return self;
}
-(void)createUserDataDatabase
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:user_data];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// construct database from external ud.sql
NSString *filePath=[[NSBundle mainBundle]pathForResource:#"ud" ofType:#"sql"];
NSString *sqlStatement=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
if(sqlite3_open([writableDBPath UTF8String], &database)==SQLITE_OK)
{
sqlite3_exec(database, [sqlStatement UTF8String], NULL, NULL, NULL);
sqlite3_close(database);
}
}
Your external sql file must contain the sql queries:
CREATE TABLE quantityInSubCountries (
refID INT,
quantity INT
);
CREATE TABLE quantityInSubRegions (
refID INT,
quantity INT
); ....
Hope it will help.
This is common methods used for Database
-(void)updateTable:(NSString *)tableName setname:(NSString *)Name setImagePath:(NSString *)imagePath whereID:(NSInteger)rid{
NSString *sqlString=[NSString stringWithFormat:#"update %# set name='%#' where id=%ld",tableName,Name,rid];
char *error;
if (sqlite3_exec(db, [sqlString UTF8String], NULL, NULL, &error)!=SQLITE_OK) {
[self closeDatabase];
NSLog(#"Faield to update");
}
else{
NSLog(#"update successfully");
}
}
-(void)deleteFrom:(NSString *)tablename whereName:(NSInteger )rid {
NSString *sqlString=[NSString stringWithFormat:#"delete from %# where id=%ld",tablename,(long)rid];
char *error;
if (sqlite3_exec(db, [sqlString UTF8String], NULL, NULL, &error)!=SQLITE_OK) {
[self closeDatabase];
NSLog(#"faield to Delete");
}
else{
NSLog(#"Deleted successfully");
}
}
-(void)insertInTable:(NSString *)tableName withName:(NSString *)name withImagePath:(NSString *)imagePath
{
NSString *sqlString=[NSString stringWithFormat:#"insert into %#(name,path)values('%#','%#')",tableName,name,imagePath];
char *error;
if (sqlite3_exec(db, [sqlString UTF8String], NULL, NULL, &error)!=SQLITE_OK) {
[self closeDatabase];
NSLog(#"Failed to insert");
}
else{
NSLog(#"Inserted succesfully");
}
}
-(NSString *)path
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir=[paths objectAtIndex:0];
return [documentDir stringByAppendingPathComponent:#"Storage.db"];
}
-(void)open{
if(sqlite3_open([[self path] UTF8String], &db)!=SQLITE_OK)
{
sqlite3_close(db);
NSLog(#"your database table has been crash");
}
else{
NSLog(#"Database open successfully");
}
}
-(void)closeDatabase
{
sqlite3_close(db);
NSLog(#"Database closed");
}
-(void)copyFileToDocumentPath:(NSString *)fileName withExtension:(NSString *)ext{
NSString *filePath=[self path];
NSFileManager *fileManager=[NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:filePath]) {
NSString *pathToFileInBundle=[[NSBundle mainBundle] pathForResource:fileName ofType:ext];
NSError *err=nil;
BOOL suc=[fileManager copyItemAtPath:pathToFileInBundle toPath:filePath error:&err];
if (suc) {
NSLog(#"file copied successfully");
}
else
{
NSLog(#"faield to copied");
}
}
else
{
NSLog(#"File allready present");
}
}
-(NSMutableArray *)AllRowFromTableName:(NSString *)tableName{
NSMutableArray *array=[[NSMutableArray alloc] init];
NSString *sqlString=[NSString stringWithFormat:#"select *from %#",tableName];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, [sqlString UTF8String], -1, &statement, nil)==SQLITE_OK) {
while (sqlite3_step(statement)==SQLITE_ROW) {
Database *tempDatabase=[[Database alloc] init];
tempDatabase.Hid=sqlite3_column_int(statement, 0);
tempDatabase.Hname =[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
tempDatabase.Hpath=[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
[array addObject:tempDatabase];
}
}
return array;
}
-(void)test
{
//Pet photos
NSString *sqlString=[NSString stringWithFormat:#"create table if not exists StorageTable(id integer primary key autoincrement,name text,path text)"];
char *error;
if (sqlite3_exec(db, [sqlString UTF8String], NULL, NULL, &error)!=SQLITE_OK) {
[self closeDatabase];
NSLog(#"Faield to blanck 1 %s",error);
}
else{
NSLog(#"Test On StorageTable Database successfully");
}
}

Query statement is not executing of sqlite database in xcode

I am using sqlite database mathFActs in my project which i create through Sqlite Database Browser and add it to Xcode. following is my code from a view controller class
- (void)viewDidLoad
{ [super viewDidLoad];
[self copyDatabaseIfNeeded];
[self getInitialDataToDisplay:[self getDBPath]];
}
- (void) copyDatabaseIfNeeded {
//Using NSFileManager we can perform many file system operations.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPth = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPth];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"mathFActs"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"mathFActs"];
}
-(void) getInitialDataToDisplay:(NSString *)databasePath{
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSLog(#"open");
const char *sql = "select Question from math ";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
NSLog(#"prepare");
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSString *addressField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(selectstmt, 0)];
//address.text = addressField;
qstn.text=addressField;
sqlite3_finalize(selectstmt);
}}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
}
when i run the project it print open but not prepare means it's not executing query statement .. plz help me to solve my problem
Try this :-
-(void) getInitialDataToDisplay:(NSString *)databasePath
{
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"open");
const char *sql = "select Question from math ";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
NSLog(#"prepare");
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSString *addressField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(selectstmt, 0)];
//address.text = addressField;
qstn.text=addressField;
}
sqlite3_reset(selectstmt);
}
else
{
NSLog(#"Error: failed to select details with message '%s'.", sqlite3_errmsg(database));
}
sqlite3_finalize(selectstmt);
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
}
EDIT :-
-(void)copyDatabaseIfNeeded
{
#try
{
NSFileManager *fmgr=[NSFileManager defaultManager];
NSError *error;
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *path=[paths objectAtIndex:0];
dbPath=[path stringByAppendingPathComponent:#"mathFActs.sqlite"];
if(![fmgr fileExistsAtPath:dbPath]){
NSString *defaultDBPath=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:#"Addict.sqlite"];
if(![fmgr copyItemAtPath:defaultDBPath toPath:dbPath error:&error])
NSLog(#"failure message----%#",[error localizedDescription]);
}
}
#catch (NSException *exception)
{
NSLog(#"Exception: %#", exception);
}
}
-(NSString *)getDBPath
{
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"mathFActs.sqlite"];
}
-(void)openDatabase
{
[self copyDatabaseIfNeeded];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
//Database Opened
NSLog(#"Database opened");
}
else
{
NSLog(#"Database cannot be opened");
}
}
-(void)closeDatabase
{
sqlite3_close(database);
}
Hope it helps you

Resources