Trying to Fetching data from sqlite database - iphone

Below is my code, i am trying to fetch data from my.sqlite database but it is not executing my if case. It always enters in else condition. What wrong thing i am doing?
I am not able to execute my if case i.e. if(sqlite3_prepare_v2(database, sqlQuerry, -1, &querryStatement, NULL)==SQLITE_OK)
sqlite3 *database;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:#"my.sqlite"];
const char* dbPath=[databasePath UTF8String];
if(sqlite3_open(dbPath, &database)==SQLITE_OK)
{
const char *sqlQuerry="SELECT * FROM Contacts;";
sqlite3_stmt *querryStatement;
if(sqlite3_prepare_v2(database, sqlQuerry, -1, &querryStatement, NULL)==SQLITE_OK)
{
NSLog(#"conversion successful....");
while (sqlite3_step(querryStatement)==SQLITE_ROW)
{
NSString *addressField = [[NSString alloc] initWithUTF8String:
(const char *)
sqlite3_column_text(querryStatement, 0)];
NSString *phoneField = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(querryStatement, 1)];
NSLog(#"DB ID :- %#",addressField);
NSLog(#"DB NAME :- %#",phoneField);
}
sqlite3_reset(querryStatement);
}
else {
NSLog(#"error while conversion....");
}
sqlite3_close(database);
}
/////////////////////////////////////////////////////////////////////////////////
I tried using FMDB and did it as bellow:
But my *s and *results object are getting nil value and while statement is not executed
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:#"my.sqlite"];
FMDatabase* database = [FMDatabase databaseWithPath:path];
[database open];
FMResultSet *s = [database executeQuery:#"SELECT COUNT(*) FROM Contacts"];
while ([s next])
{
int totalCount = [s intForColumnIndex:0];
NSLog(#"Count : %i", totalCount);
}
FMResultSet *results = [database executeQuery:#"select * from Contacts"];
while([results next])
{
NSString *contact_id = [results stringForColumn:#"contact_id"];
NSString *name = [results stringForColumn:#"name"]; //
NSLog(#"User: %# - %#",name, contact_id);
}
[database close];

Replace your first six lines by the following code:
sqlite3 *database;
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:#"my.sqlite"];
NSLog(#"DATABASE PATH=%#",databasePath);
NSFileManager *fn=[NSFileManager defaultManager];
NSError *error;
BOOL success=[fn fileExistsAtPath:databasePath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"my.sqlite"];
success = [fn copyItemAtPath:defaultDBPath toPath:databasePath error:&error];
}
const char *dbPath=[databasePath UTF8String];
if(sqlite3_open(dbPath, &database)==SQLITE_OK)
{
//. . . . your code...//
}

If you have a problem with any sqlite API then you need to report the error using sqlite3_errmsg() (reference) and this will help you track down your problem.
Change your code to report the error and update your question with the log output:
if (sqlite3_open(dbPath, &database) == SQLITE_OK)
{
...
}
else
{
NSLog("Failed to open database '%#': %s", databasePath, sqlite3_error(database));
}
According to the documentation for sqlite3_open() (here):
.... Otherwise an error code is returned. The sqlite3_errmsg() or
sqlite3_errmsg16() routines can be used to obtain an English language
description of the error following a failure of any of the
sqlite3_open() routines.

I found where I was going wrong. I created & inserted data to my database using Core Data. At the time of fetching I wanted to fire very complex queries, so I had to switch to SQLite. I was doing everything fine but getting error: Table not found.
The actual problem was that CoreData changed every table name of my database with a name prepending a "z", so my table name Contacts changed to ZContacts and column names in similar manner. When I opened my sqlite database in SQLite Manager I found where I was wrong.

Related

how can i update sqlite database

I want to update records from several textfiels in detail viewcontroller, but when I cliCk on update button, its goes to failed to update database. pls suggest me.
-(IBAction)updateQuery:(id)sender
{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &Information) == SQLITE_OK)
{
NSString *updateSQL = [NSString stringWithFormat: #"update CONTACTS set address=\"%#\",phone=\"%#\",imageUrl=\"%#\" WHERE name=\"%#\"",daddress.text,dphone.text,durl.text,dname.text];
const char *update_stmt = [updateSQL UTF8String];
sqlite3_prepare_v2(Information, update_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
dstatuslabel.text=#"updated successfully";
}
else
{
dstatuslabel.text = #"Failed to update contact";
}
sqlite3_finalize(statement);
sqlite3_close(Information);
}
}
NSString *updateSQL = [NSString stringWithFormat: #"update CONTACTS set address='%#',phone='%#',imageUrl='%#' WHERE name='%#'",daddress.text,dphone.text,durl.text,dname.text];
In my method i use following way its working :
-(BOOL)updateProfileFromCreatorId:(int)creatorProfileId{
char *st,*errorMsg;
NSLog(#"profile.creatorProfileId:%d",creatorProfileId);
st = sqlite3_mprintf("UPDATE Profile SET `CreatorID`=%d WHERE `CreatorID`= 1"
,creatorProfileId //username
);
NSLog(#"updateQUERY: %#",[NSString stringWithUTF8String:st]);
int ret = sqlite3_exec(rlraDb, st, NULL, NULL, &errorMsg);
if (ret != SQLITE_OK) {
sqlite3_free(errorMsg);
sqlite3_free(st);
return NO;
}
sqlite3_free(st);
return YES;
}
Add the Sqlite DB like any other file in your application bundle
Copy it to documents directory via code and use it (Method :checkAndCreateDatabase ) .The purpose of this is that updating content in sqlite is possible in Documents directory only
-(void) checkAndCreateDatabase
{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:_databasePath];
// If the database already exists then return without doing anything
if(success) return;
// If not then proceed to copy the database from the application to the users filesystem
// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:_databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:nil];
}
- (id)init {
if ((self = [super init]))
{
_databaseName = DB_NAME;
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
_databasePath = [documentsDir stringByAppendingPathComponent:_databaseName];
if (sqlite3_open([[self dbPath] UTF8String], &_database) != SQLITE_OK)
{
[[[UIAlertView alloc]initWithTitle:#"Missing"
message:#"Database file not found"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil]show];
}
}
return self;
}
Try this...It should work...
1) Please make sure you are copying the db from your bundle to documents directory before updating the db...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"YOUR DBNAME.sqlite"];
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:filePath];
// If the database already exists then return without doing anything
if(success) return;
// If not then proceed to copy the database from the application to the users filesystem
// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:_databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:nil];
}
2)Step 2: Update
sqlite3 *database;
sqlite3_stmt *updateStmt=nil;
const char *dbpath = [filePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *updateSQL = [NSString stringWithFormat: #"update CONTACTS set address=\"%#\",phone=\"%#\",imageUrl=\"%#\" WHERE name=\"%#\"",daddress.text,dphone.text,durl.text,dname.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &updateStmt, NULL);
if (sqlite3_step(updateStmt) == SQLITE_DONE)
{
NSLog(#"updated");
}
}

Sqlite INSERT INTO does not proceed in iphone but on simulator and ipod touch? [duplicate]

This question already has answers here:
SQLite insert works in simulator but not on device
(2 answers)
Closed 9 years ago.
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSBundle mainBundle] pathForResource:#"etkYeni2" ofType:#"sqlite"];
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK){
NSLog(#"icerdeyim");
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO etk (etkTip) VALUES ('%#')",yeniEkleLabel.text];
const char *query_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"OK INSERTED");
} else {
NSLog(#"NOT INSERTED !!");
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
Here is my part of the code which I getting a string from the textbox and inserted it to the sqlite database. I created the database from the firefox extention sqlite manager and added it to the app. It is running as I expected in simulator and ipod touch how I wanted (inserts elements and I can see them when I used SELECT query ), but it is not inserts an element on iphone . My ipod touch is on iOS 5 and iphone is on iOS 6. Is it because of the version of iOS or iphone and ipod touch is pretends differently to the sqlite or what ? I read most of the answers of this problem and still don't get the solution. Could someone can help me in this situation ?
Thanks ..
Your database not Copied at phone directory u need to add that database.
using this code.
-(void)createdatabase
{
NSString *databaseName = #"Card.sqlite"; // Database Name
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = documentPaths[0];
NSLog(#"Dir : %# ",documentsDir);
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager] ;
success = [fileManager fileExistsAtPath:databasePath];
if(success)
return;
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
NSLog(#"%#",databasePathFromApp);
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
add your sqlite file into mainbundle.
thsi will really helpful.
Please try to use this one. If you wanna insert data in sqlite in that case you must create your Database and insert query using this method.I hope it will be helpful..
- (void)executeQuery:(NSString *)insertQuery
{
sqlite3_stmt *statement;
if (sqlite3_open([[self databaseFilePath] UTF8String],&sqliteDB) == SQLITE_OK)
{
if(sqlite3_prepare_v2(sqliteDB,[insertQuery UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
if(sqlite3_step(statement) != SQLITE_DONE)
{
sqlite3_finalize(statement);
}
}
else
NSLog(#"query Statement Not Compiled");
sqlite3_finalize(statement);
sqlite3_close(sqliteDB);
}
else
NSLog(#"Database Not Opened");
}
- (NSString *)databaseFilePath
{
databaseName=#"abc.sqlite";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *path = [paths objectAtIndex:0];
return [path stringByAppendingPathComponent:databaseName];
}

iOS 6: SQLite db doesn't work

I always use this code to open a sqlite db in my iPhone application, but now with iOS6 this code doesn't work. The function: sqlite3_prepare_v2 fails but I don't understand why!
I also don't understand why if I try to change the name: "gamer.sqlite" of sqlite db with another name of an not existent file, the function: 'sqlite3_open' return again SQLITE_OK value.
This is my code:
-(NSMutableArray*)view_table
{
const char *sql;
NSMutableArray *content=[[NSMutableArray alloc] initWithObjects:nil];
[self msgbox:#"eseguo"];
/*elementi da visualizzare nella tabella*/
if(sqlite3_open([databasePath UTF8String],&database)==SQLITE_OK)
{
[self msgbox:#"opened"];
sql = "SELECT * FROM list_gamer";
if (sqlite3_prepare_v2(database,sql, -1, &selectstmt, NULL) == SQLITE_OK)
{
[self msgbox:#"query eseguita"];
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
[content addObject:[NSString stringWithFormat:#"%s",sqlite3_column_text(selectstmt,0)]];
}
}
}
return content;
}
- (void)viewDidLoad{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [[documentsDir stringByAppendingPathComponent:#"gamer.sqlite"] copy];
if(![[NSFileManager defaultManager] fileExistsAtPath:databasePath])
{
NSFileManager *fileManager = [NSFileManager defaultManager];
int success = [fileManager fileExistsAtPath:databasePath];
if(success)
{
[fileManager removeItemAtPath:databasePath error:nil];
return;
}
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"gamer.sqlite"];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDir = [documentPaths objectAtIndex:0];
}
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
}
-(IBAction)start_game:(id)sender{
self.view=frmgame;
[self view_table];
}
Not exactly a direct answer but i personally really love using fmbd to help manage sqlite & error.
Fmdb is an Objective-C wrapper around SQLite: http://sqlite.org/
https://github.com/ccgus/fmdb

Getting error while trying to fetch and insert data into SQLite database

I am creating an application where I am using SQLite database to save data. But when I run my application I get the following errors:
#interface TDatabase : NSObject {
sqlite3 *database;
}
+(TDatabase *) shareDataBase;
-(BOOL) createDataBase:(NSString *)DataBaseName;
-(NSString*) GetDatabasePath:(NSString *)database;
-(NSMutableArray *) getAllDataForQuery:(NSString *)sql forDatabase:(NSString *)database;
-(void*) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1;
#end
#import "TDatabase.h"
#import <sqlite3.h>
#implementation TDatabase
static TDatabase *SampleDataBase =nil;
+(TDatabase*) shareDataBase{
if(!SampleDataBase){
SampleDataBase = [[TDatabase alloc] init];
}
return SampleDataBase;
}
-(NSString *)GetDatabasePath:(NSString *)database1{
[self createDataBase:database1];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:database1];
}
-(BOOL) createDataBase:(NSString *)DataBaseName{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DataBaseName];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return success;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DataBaseName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!!!" message:#"Failed to create writable database" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
[alert release];
}
return success;
}
-(NSMutableArray *) getAllDataForQuery:(NSString *)sql forDatabase:(NSString *)database1{
sqlite3_stmt *statement = nil ;
NSString *path = [self GetDatabasePath:database1];
NSMutableArray *alldata;
alldata = [[NSMutableArray alloc] init];
if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
{
NSString *query = sql;
if((sqlite3_prepare_v2(database,[query UTF8String],-1, &statement, NULL)) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSMutableDictionary *currentRow = [[NSMutableDictionary alloc] init];
int count = sqlite3_column_count(statement);
for (int i=0; i < count; i++) {
char *name = (char*) sqlite3_column_name(statement, i);
char *data = (char*) sqlite3_column_text(statement, i);
NSString *columnData;
NSString *columnName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
if(data != nil)
columnData = [NSString stringWithCString:data encoding:NSUTF8StringEncoding];
else {
columnData = #"";
}
[currentRow setObject:columnData forKey:columnName];
}
[alldata addObject:currentRow];
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return alldata;
}
-(void*) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1{
sqlite3_stmt *statement = nil ;
NSString *path = [self GetDatabasePath:database1];
if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
{
if((sqlite3_prepare_v2(database,[insertSql UTF8String],-1, &statement, NULL)) == SQLITE_OK)
{
if(sqlite3_step(statement) == SQLITE_OK){
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return insertSql;
}
NSString *sql = #"select * from Location";
const location = [[TDatabase shareDataBase] getAllDataForQuery:sql forDatabase:#"journeydatabase.sqlite"];//1
NSString* insertSql = [NSString stringWithFormat:#"insert into Location values ('city','name','phone')"];//2
const insert =[[TDatabase shareDataBase] inseryQuery:insertSql forDatabase:#"journeydatabase.sqlite"];//3
in line no 1,2,3 I get the same error:
initializer element is not constant
What might be the problem?
#rani writing your own methods to deal with sqlite database is very painstaking. You should use fmdb wrapper class or use core data. I personally prefer fmdb. Initially I was doing the same way you were. I found about fmdb here. After using it I had to write very little code whenever I have to deal With sqlite db.

create sqlite db programmatically in iphone sdk

hai i a'm trying to create a sqlite database programmatically at the run time. can anybody say how to create it in iphone sdk.
Just call the sqlite3_open function it will create a database if no database exist on the path.
// generate databasePath programmatically
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
// your code here
}
post a comment if you need more code example on this
-(void)viewDidLoad
{
[super viewDidLoad];
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"contacts.sqlite"]];
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 CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"if");
}
sqlite3_close(contactDB);
} else
{
NSLog(#"else");
}
}
[filemgr release];
}
-(IBAction)table
{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"contacts.sqlite"]];
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 LIST (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"tables failed");
// status.text = #"Failed to create table";
}
sqlite3_close(contactDB);
}
else
{
NSLog(#"tables failed");
//status.text = #"Failed to open/create database";
}
}
[filemgr release];
}
import in .m file #import sqlite3.h and add framework in ur project libsqlite3.0.dylib
firstly create NSObject class and named it Database.
in .h class
#interface database : NSObject
{
NSString *databasePath;
NSString *databaseName;
sqlite3 *myDatabase;
NSArray *documentPaths;
NSString *documentsDir;
}
//---initial methods-------
-(void)createDatabaseIfNeeded;
//-----------------path find method---------------------//
-(void)pathFind;
//-----------------write value----------------------//
-(void)writeValueInSettings:(NSMutableArray *)arrayvalue;
//-------------------fetch value from setting table------------//
-(NSMutableArray *)fetchValue;
//-------------------update value---------------------//
-(void)updateSetting:(NSArray *)arr;
.m class write
-(id)init
{
if((self=[super init]))
{
[self createDatabaseIfNeeded];
}
return self;
}
//-----------create database if needed method--------------//
-(void)createDatabaseIfNeeded
{
[self pathFind];
BOOL success;
NSFileManager *filemgr = [NSFileManager defaultManager];
success=[filemgr fileExistsAtPath:databasePath];
if (success)return;
NSLog(#"not success");
//Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
// Copy the database from the package to the users filesystem
[filemgr copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
//----------------path find-----------------//
-(void)pathFind
{
databaseName = #"accDataBase.DB";
// Get the path to the documents directory and append the databaseName
documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
}
//------------------write value in setting----------------//
-(void)writeValueInSettings:(NSMutableArray *)arrayvalue
{
NSLog(#"%#",arrayvalue);
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
database *objectDatabase=[[database alloc]init];
NSString *stringvalue2=[objectDatabase countValue];
[objectDatabase release];
int intvalue1=[stringvalue2 intValue];
intvalue1=intvalue1+1;
NSLog(#"opened");
NSString *sql1;
sql1=[[NSString alloc] initWithFormat:#"insert into setting values('%i','%i','%i','%#','%i','%i','%#','%i','%i','%i','%i','%i','%i','%#');",intvalue1,
[[arrayvalue objectAtIndex:0] intValue],[[arrayvalue objectAtIndex:1] intValue],[arrayvalue objectAtIndex:2],[[arrayvalue objectAtIndex:3] intValue],[[arrayvalue objectAtIndex:4]intValue ],[arrayvalue objectAtIndex:5],[[arrayvalue objectAtIndex:6]intValue],[[arrayvalue objectAtIndex:7]intValue ],[[arrayvalue objectAtIndex:8] intValue],[[arrayvalue objectAtIndex:9] intValue],[[arrayvalue objectAtIndex:10]intValue ],[[arrayvalue objectAtIndex:11]intValue],[arrayvalue objectAtIndex:12]];
char *err1;
if (sqlite3_exec(myDatabase,[sql1 UTF8String],NULL,NULL,&err1)==SQLITE_OK)
{
NSLog(#"value inserted:");
}
[sql1 release];
sqlite3_close(myDatabase);
}
}
//------------fetch all value-------------//
-(NSMutableArray *)fetchValue
{
NSMutableArray *list=nil;
list=[[[NSMutableArray alloc]init] autorelease];
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
NSString *sql=[NSString stringWithFormat: #"select * from setting where primaryKey=1"];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(myDatabase, [sql UTF8String], -1,&statement, NULL)==SQLITE_OK)
{
if(sqlite3_step(statement)==SQLITE_ROW)
{
for(int i=0;i<=13;i++)
{
char *pass=(char*)sqlite3_column_text(statement,i);
NSString *msg=[[NSString alloc]initWithUTF8String:pass];
[list addObject:msg];
[msg release];
}
}
sqlite3_finalize(statement);
}
sqlite3_close(myDatabase);
}
return list;
}
//----------------update setting table method---------------//
-(void)updateSetting:(NSArray *)arr
{
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
NSLog(#"opened");
sqlite3_stmt *compiledStmt;
// NSLog(#"%#",arr);
NSString *sqlStmt=[NSString stringWithFormat:#"UPDATE setting SET ragular=%i,cycle=%i, flow='%#', hour=%i,minute=%i,formate='%#' ,tenminute=%i ,thirtyminute=%i,sixtymin=%i, twentymin=%i, fourtyfivemin=%i ,other='%#',formatemessage ='%#' WHERE primaryKey=%i;",[[arr objectAtIndex:0]intValue],[[arr objectAtIndex:1]intValue],[arr objectAtIndex:2],[[arr objectAtIndex:3]intValue],[[arr objectAtIndex:4]intValue],[arr objectAtIndex:5],[[arr objectAtIndex:6]intValue],[[arr objectAtIndex:7]intValue],[[arr objectAtIndex:8]intValue],[[arr objectAtIndex:9]intValue],[[arr objectAtIndex:10]intValue],[arr objectAtIndex:11],[arr objectAtIndex:12],1];
// NSLog(#"%#",sqlStmt);
if(sqlite3_prepare_v2(myDatabase, [sqlStmt UTF8String],-1,&compiledStmt, NULL)==SQLITE_OK)
{
NSLog(#"updateding......cycle");
}
sqlite3_step(compiledStmt);
sqlite3_close(myDatabase);
}
}