how can i update sqlite database - iphone

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");
}
}

Related

App crashes when deleting data from SQLite in iPhone5

I developed a SQLite database when application "didFinishLoading" database cleared and calls a web service to get data and insert it into the database. It's working fine in all iPhone and iPad devices, but on iPhone5, it crashes when deleting data from the database.
Here, tableNamesArray means tables in SQLite.
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
for (int i = 0; i < [tableNamesArray count]; i++)
{
NSString *querySQL = [NSString stringWithFormat:#"DELETE FROM %#", [tableNamesArray objectAtIndex:i]];
NSLog(#"querySQL %#", querySQL);
// SELECT QuationID,Quation FROM QuationsTable WHERE GroupID="Group0"
const char *query_stmt = [querySQL UTF8String];
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &compiledStatement, NULL) == SQLITE_OK)
{
}
if (sqlite3_step(compiledStatement) != SQLITE_DONE )
{
}
else
{
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(contactDB);
}
Please help me.
Use This function to copy your database into cache directory.
-(void)createDBcopy:(NSString*)fileName
{
// 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];
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *DBPath=[documentsDirectory stringByAppendingPathComponent:fileName];
//DBPath = [DBPath stringByAppendingString:#".sqlite"];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:DBPath];
// 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:fileName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:DBPath error:nil];
[fileManager release];
}
And use it as:
[yourClassObjectWhereTheMethodIsWritten createDBcopy:#"yourDB.sqlite"];
You should use it at didFinishLaunchWithOption in Appdelegate.

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];
}

sqlite3_prepare_v2() == SQLITE_OK returns NO and existing table is not found

I am developing an iphone application which using sqlite3 database file. and i am using following code to select from sqlite3 database ;
NSString* dbYolu = [NSString stringWithFormat:#"%#/emhdb3.sqlite3",NSHomeDirectory()];
sqlite3* db;
NSLog(#"%# dbyolu : ", dbYolu);
if (sqlite3_open([dbYolu UTF8String], &db) == SQLITE_OK)
{
NSString *query = [NSString stringWithFormat: #"SELECT username, mobile FROM peopleto WHERE namesurname=\"%#\"", name.text];
NSLog(#"%# : query", query);
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, nil) == SQLITE_OK) // statement stmt returns null and returns SQLITE_OK = FALSE.
{
NSLog(#"stepped in SQLITE_OK is TRUE");
while (sqlite3_step(stmt) == SQLITE_ROW)
{
NSString* ders_kodu = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 0)];
double not = sqlite3_column_double(stmt, 1);
NSLog(#"%# : %f", ders_kodu, not);
}
}
else
{
NSLog(#"%# - but failed", stmt);
}
sqlite3_finalize(stmt);
}
else
NSLog(#"db could not be opened");
it fails at the "sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, nil) == SQLITE_OK" point above. and the error is : "Error:No such table : peopleto. But it successfully returns the content of table when i run this query in sql browser. I mean this query is correct and working.
btw, I get the file with pathname with the following code on viewLoad
- (void)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: #"emhdb3.sqlite3"]];
NSLog(#"dbpath : %#", databasePath);
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
NSLog(#"db not found");
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSLog(#"SQLITE_OK is passed");
//.... some codes here, doesn't metter for me because SQLITE_OK = true
} else {
status.text = #"Failed to open/create database";
}
}
else if ([filemgr fileExistsAtPath:databasePath] == YES)
{
NSLog(#"i found the file here : %s",[databasePath UTF8String]);
}
NSLog(#"completed");
[super viewDidLoad];
}
I have the database file in my project folder and added to the project.
What i am missing?
Thanks
///////
i am sorry for updating my question but stackoverflow does not allow me to add new ,
please find my update below ;
Here is the updated version of the code :
viewLoad part;
- (void)viewDidLoad
{
[self createEditableCopyOfDatabaseIfNeeded];
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:#"emhdb3.sqlite3"]];
NSLog(#"dbpath : %#", databasePath);
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 peopleto (pId INTEGER PRIMARY KEY AUTOINCREMENT, namesurname TEXT, mobile TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
status.text = #"Failed to create table";
}
sqlite3_close(contactDB);
} else {
status.text = #"Failed to open/create database";
}
}
else if ([filemgr fileExistsAtPath:databasePath] == YES)
{
NSLog(#"%s is filepath",[databasePath UTF8String]);
}
NSLog(#"checkpoint 4");
[super viewDidLoad];
}
buraya başka birşey yaz
- (void)createEditableCopyOfDatabaseIfNeeded {
NSLog(#"entered createEditableCopyOfDatabaseIfNeeded");
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"emhdb3.sqlite3"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)
{
NSLog(#"success == YES returned");
return;
}
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"emhdb3.sqlite3"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSLog( #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
else{
NSLog(#"checkpoint 2");
}
}
and the part that select query is performed ;
-(IBAction)findcontact2:(id)sender
{
NSString *dbYolu = databasePath;
sqlite3* db;
NSLog(#"%# dbyolu : ", dbYolu);
if (sqlite3_open([dbYolu UTF8String], &db) == SQLITE_OK)
{
NSString *query = [NSString stringWithFormat: #"SELECT namesurname, mobile FROM peopleto"]; //any query
NSLog(#"%# : query", query);
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, nil) == SQLITE_OK)
{
NSLog(#"SQLITE is OK");
while (sqlite3_step(stmt) == SQLITE_ROW)
{
NSString* ders_kodu = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 0)];
double not = sqlite3_column_double(stmt, 1);
NSLog(#"%# : %f", namesurname, mobile);
}
}
else
{
NSLog(#"Error=%s",sqlite3_errmsg(db)); // error message : Error=no such table: peopleto
NSLog(#"%# - is stmt", stmt); //stmt is null
}
sqlite3_finalize(stmt);
}
else
NSLog(#"could not open the db");
}
As i pointed above, the error is Error=no such table: peopleto and stmt is returned null
Are you copying your SQL file to documents, if not you need to do that first. While adding SQL file to project, it is added in your bundle and not in documents directory. YOu need to copy that first
- (void)createEditableCopyOfDatabaseIfNeeded {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"bookdb.sql"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)
return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"bookdb.sql"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSLog( #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
Please check the DB which is in your main bundle contains the table then try to copy it to resource folder and apply the above

unable to insert in sqlite database for iphone when app is terminated and started again

-(void)checkAndCreateDatabase{
NSLog(#"hello");
databaseName = #"EMAP234.sql";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
NSLog(#"database path %#",databasePath);
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];
[fileManager release];
}
-(void)insertIntoDatabase:(NSString *)insertCommand{
// Setup the database object
sqlite3 *database;
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = [insertCommand UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
NSLog(#"inserted");
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
the app works fine for the first time but when i restart it , it can read the earlier values but cannot insert new ones ... pls help
here is how I am calling this....
DatabaseOperations *obj=[[DatabaseOperations alloc]init];
[obj checkAndCreateDatabase];
NSLog(#"patient ID %d",[obj readMaxPatientIDFromDatabase]);
patientID= [NSString stringWithFormat:#"HCI%d", ([obj readMaxPatientIDFromDatabase]+1)];
NSLog(#"patient ID %#",patientID);
[self generatePatientInsertCommand];
[obj insertIntoDatabase:patientInsertCommand];
[self generateCarrierInsertCommand];
[obj insertIntoDatabase:carrierInsertCommand];
[self generateSyncTableInsertCommand];
[obj insertIntoDatabase:syncTableInsertCommand];
NSString *msg=#"your PatientID is";
[obj release];
msg=[msg stringByAppendingString:patientID];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"REGISTERED" message:msg delegate:self cancelButtonTitle:#"ok" otherButtonTitles: nil];
[alert show];
[alert release];
Hello Ankit I used your code and called
[self checkAndCreateDatabase];
[self insertIntoDatabase:[NSString stringWithFormat:#"INSERT INTO User (uId,userName,userBirthday) VALUES (\"%d\", \"%#\", \"%#\" )",3,#"Admin",#"2010-12-01"]];
The only thing I changed is using a different database file which I choose in checkAndCreateDatabase function by
-(void)checkAndCreateDatabase{
NSLog(#"hello");
databaseName = #"MasterDB.sqlite";
....
}
The code worked fine for every insert with a new uId. Please check your read Function and If Possible then paste the code for read function along with the above code and the way you call these two viz read and insert functions.

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);
}
}