delete row from call_history.db on iOS4 - iphone

I'm trying to delete rows from call_history.db. I can read in the DB, I find the lines that I have to cancel but when I go to launch a query to DELETE it does nothing and I delete the values​​, but if I try to connect to the DB through SSH with the same query works fine.
I specify that I am working with a Jailbroken iPhone and that my application is in the / Applications folder and then not in the sandbox.
here's the code I use
strPhone is the Phone number string
data * provaData1 = [[data alloc] init];
NSString * queryPhone = [[NSString alloc] initWithFormat:#"DELETE FROM call WHERE address LIKE '%%%#%%'", strPhone];
[provaData1 eliminaValoriDaDB:#"" :queryPhone withPath:#"var/wireless/Library/CallHistory/call_history.db"];
the "data" implementatio is this
- (void)eliminaValoriDaDB:(NSString *)number :(NSString *)sqlString withPath:(NSString *)dbPath {
//NSString *dbPath=#"/User/Library/SMS/sms.db";
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
if(delStmt == nil)
{
const char *sql = [sqlString UTF8String];
//const char *sql = [sqlDel UTF8String];
if(sqlite3_prepare_v2(database, sql, -1, &delStmt, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating del statement. '%s'", sqlite3_errmsg(database));
}
if (![number isEqualToString:#""])
{
sqlite3_bind_int(delStmt, 1, [number intValue]);
}
if (SQLITE_DONE!= sqlite3_step(delStmt)) {
NSAssert1(0, #"Error while deleting. '%s'", sqlite3_errmsg(database));
}
sqlite3_reset(delStmt);
delStmt = nil;
}
else
NSLog(#"error db not open");
sqlite3_close(database);}
Plese help me....I do not know what to do
Thanks Andrea

NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
NSArray *subPaths = [fileManager subpathsAtPath:#"/private/var/wireless/Library/CallHistory"];
for (NSString *aPath in subPaths) {
BOOL isDirectory;
[fileManager fileExistsAtPath:aPath isDirectory:&isDirectory];
if (isDirectory) {
NSDictionary *attrib = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithUnsignedLong:775], NSFilePosixPermissions, nil ];
NSError *error = nil;
[fileManager setAttributes:attrib ofItemAtPath:aPath error:error];
if (error)
{
NSLog(#"error: %#", error);
}
}
}

Related

Images not storing to database

I stored some images in my server. And try to get this images from URL and store to local database then try to access. But the images are not storing to database. But when i use log it displaying inserting all the values. But i can't shown in db via SQLiteManager
code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:#"button.png"] forState:UIControlStateNormal];
// [overlayButton setFrame:CGRectMake(80, 420, 60, 30)];
[btn setFrame:CGRectMake(50, 50, 30, 30)];
[btn addTarget:self action:#selector(click:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
Button click:
-(void)click:(id)sender{
NSLog(#"click");
NSString *databasePath=[[NSBundle mainBundle]pathForResource:#"db1" ofType:#"sqlite"];
NSError *err=nil;
NSFileManager *fm=[NSFileManager defaultManager];
NSArray *arrPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, -1);
NSString *path=[arrPaths objectAtIndex:0];
NSString *path2= [path stringByAppendingPathComponent:#"db1.sqlite"];
bool success=[fm copyItemAtPath:databasePath toPath:path2 error:&err];
if(!success){
NSLog(#"file copied successfully");
}
/*
if(![fm fileExistsAtPath:path2])
{
bool success=[fm copyItemAtPath:databasePath toPath:path2 error:&err];
if(success)
NSLog(#"file copied successfully");
else
NSLog(#"file not copied");
}
*/
NSURL *URL = [NSURL URLWithString:#"http://myserver.net/projects/mobile/jsonstring.php"];
NSError *error;
NSString *stringFromFileAtURL = [[NSString alloc]
initWithContentsOfURL:URL
encoding:NSUTF8StringEncoding
error:&error];
//NSLog(#"response is %#", stringFromFileAtURL);
// NSString *path = [documentsDirectory stringByAppendingPathComponent:#"db1.sqlite"];
//NSLog(#"filepath %#",path);
NSString *path1 = [path stringByAppendingPathComponent:#"db1.sqlite"];
//NSDictionary *jsonDict = [stringFromFileAtURL JSONValue];
//array
NSArray *userData = [stringFromFileAtURL JSONValue];
[stringFromFileAtURL release];
int i = 0;
BOOL notExist = TRUE;
sqlite3_stmt *statement, *addStmt;
for (NSArray *skarray in userData) {
//NSLog(#"test");
if(i == 0){
//insert all main category
for (NSDictionary *tuser in skarray) {
//write all this in the table
//if already exists in data base id then overwrite the name
//category table
//NSLog(#"CategoryId is %#",[tuser objectForKey:#"cat_id"]);
//NSLog(#"CategoryName is %#",[tuser objectForKey:#"cat_name"]);
if (sqlite3_open([path1 UTF8String], &database) == SQLITE_OK) {
const char *sql = [[NSString stringWithFormat:#"SELECT id FROM categories where id = '%#'",[tuser objectForKey:#"id"]] cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(#"categories select is %s", sql);
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
notExist = TRUE;
while (sqlite3_step(statement) == SQLITE_ROW) {
notExist = FALSE;
}
}
if(notExist){
//NSLog(#"cat id does not exist");
const char *sqlInsert = [[NSString stringWithFormat:#"insert into categories (id,cat_name,order_by) values('%#','%#','%#')", [tuser objectForKey:#"id"], [tuser objectForKey:#"cat_name"],[tuser objectForKey:#"order_by"]] cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(#"categories insert is %s", sqlInsert);
if(sqlite3_prepare_v2(database, sqlInsert, -1, &addStmt, NULL) == SQLITE_OK)
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
if(SQLITE_DONE == sqlite3_step(addStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
}
}
}
}
if(i == 1){
//insert all main category
for (NSDictionary *tuser in skarray) {
//write all this in the table
//if already exists in data base id then overwrite the name
//category table
//NSLog(#"CategoryId is %#",[tuser objectForKey:#"cat_id"]);
//NSLog(#"CategoryName is %#",[tuser objectForKey:#"cat_name"]);
if (sqlite3_open([path1 UTF8String], &database) == SQLITE_OK) {
const char *sql = [[NSString stringWithFormat:#"SELECT product_image FROM product where cat_id = '%#'",[tuser objectForKey:#"id"]] cStringUsingEncoding:NSUTF8StringEncoding];
// NSLog(#"product select is %s", sql);
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
notExist = TRUE;
while (sqlite3_step(statement) == SQLITE_ROW) {
notExist = FALSE;
}
}
if(notExist){
//NSLog(#"cat id does not exist");
// imgData = UIImagePNGRepresentation([tuser objectForKey:#"product_image"]);
// sqlite3_bind_blob(addStmt, 6, [imgData bytes], [imgData length], NULL);
const char *sqlInsert = [[NSString stringWithFormat:#"insert into product (id, cat_id,product_image,order_by) values ('%#','%#','%#','%#')", [tuser objectForKey:#"id"], [tuser objectForKey:#"cat_id"],[tuser objectForKey:#"product_image"],[tuser objectForKey:#"order_by"]] cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(#"product insert %s", sqlInsert);
if(sqlite3_prepare_v2(database, sqlInsert, -1, &addStmt, NULL) == SQLITE_OK)
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
if(SQLITE_DONE == sqlite3_step(addStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
}
}
}
}
if(i == 2){
//insert all main category
for (NSDictionary *tuser in skarray) {
NSLog(#"version id is %#",[tuser objectForKey:#"product_id"]);
const char *sqlInsert = [[NSString stringWithFormat:#"insert into version_app (id) values ('%#')", [tuser objectForKey:#"product_id"]] cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(#"stmt is %s", sqlInsert);
if(sqlite3_prepare_v2(database, sqlInsert, -1, &addStmt, NULL) == SQLITE_OK)
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
if(SQLITE_DONE == sqlite3_step(addStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
}
}
i++;
}
}
Do you see anything wrong here:
bool success=[fm copyItemAtPath:databasePath toPath:path2 error:&err];
if(!success){
NSLog(#"file copied successfully");
}

sqlite3_prepare error #26

I have following code (modified code from this tutorial):
-(NSMutableArray *) getChampionDatabase
{
NSMutableArray *championsArray = [[NSMutableArray alloc] init];
#try {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *databasePath = [[NSBundle mainBundle]pathForResource: #"Champions Database" ofType:#"sqlite"];
BOOL success = [fileManager fileExistsAtPath:databasePath];
if (!success)
{
NSLog(#"cannot connect to Database! at filepath %#",databasePath);
}
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "SELECT CHAMPION_ID,CHAMPION_NAME,CHAMPION_IMG FROM CHAMPIONS";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(database, sql, -1, &sqlStatement, NULL) == SQLITE_OK)
{
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
championList *ChampionList = [[championList alloc]init];
ChampionList.championId = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,0)];
ChampionList.championName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
ChampionList.championImage = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 2)];
[championsArray addObject:ChampionList];
}
}
else
{
NSLog(#"problem with database prepare");
}
}
else
{
NSLog(#"problem with database openning");
}
}
#catch (NSException *exception)
{
NSLog(#"An exception occured: %#", [exception reason]);
}
#finally
{
return championsArray;
}
}
After running this code i always have output : "problem with database prepare"
Then i tried to check error number of sqlite3_prepare by following code:
int ret = sqlite3_prepare(database, sql, -1, &sqlStatement, NULL);
if (ret != SQLITE_OK) {
NSLog(#"Error calling sqlite3_prepare: %d", ret);
}
output: "Error calling sqlite3_prepare: 26"
error 26 - /*File opened that is not a database file */
File have sqlite 3 version
how is this possible? file extension is .sqlite and i can modify it in sqlite manager
Make sure you added your DB to the ressource bundle of your project and don't put any space in your name of your DB. For example use a name like champion_db.sqlite.

Unable to update database

I'm having trouble updating my database. I believe it's due to it possibly being read only, however I am unsure. I created my database in my console, and the code below adds the database to the project folder rather than referencing it externally. Here is the code to transfer the file to the project folder
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
databaseName = #"databasenew.sql";
/* copy over to phone code */
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
NSString *sqlFile =[documentDirectory stringByAppendingPathComponent:#"databasenew.sql"];
if (![[NSFileManager defaultManager] fileExistsAtPath:sqlFile]) {
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
NSError *error = nil;
[[NSFileManager defaultManager] copyItemAtPath:bundleSql toPath:sqlFile error:&error];
if (error) {
NSLog(#"Could not copy json file: %#", error);
}
else{
NSLog(#"yea");
}
}
else{
NSLog(#"transfer complete");
}
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
databasePath = bundleSql;
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
Here is the code where I try to update
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"Message"])
{
NSLog(soapResults);
NSString *convertString = soapResults;
check = [convertString intValue];
NSLog(#"user is");
NSLog(user);
if(check > 0){
databaseName = #"databasenew.sql";
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
databasePath = bundleSql;
sqlite3 *database;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "UPDATE people set user = 'munch'";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
NSLog(#"success");
NSLog(soapResults);
BOOL success = sqlite3_step(compiledStatement);
if (success != SQLITE_DONE) {
BOOL myBool=YES;
NSLog([NSString stringWithFormat:#"My Bool value : %d",success]);
}
}else{
NSLog(#"the fail ispreparing something");
NSAssert1(0, #"Error while creating update statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_finalize(compiledStatement);
}else{
NSLog(#"fail");
}
sqlite3_close(database);
NSString *string = [NSString stringWithFormat:#"%d", check];
NSLog(string);
NSLog(#"lolololol");
check = 0;
[self Bootup];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Problem!" message:#"Incorrect Username or Password"
delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:#"Yes", nil];
[alert show];
[alert release];
}
// gotoContent = checkConfirm;
}
if( [elementName isEqualToString:#"ValidateUserResponse"])
{
if(!soapResults)
{
soapResults = [[NSMutableString alloc] init];
NSLog(soapResults);
NSLog(#"above is soap validate user");
}
recordResults = TRUE;
}
}
I've done my NDlog debugging and it says "success" as it should if the code for updating is successful, however the database itself does not update. What is the reason for this?
You are forgeting some code for update statement
//the binding part is missing in your code , you need to write after Prepare statement.
sqlite3_bind_text(compiledStatement, 1, [string UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(compiledStatement))
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
sqlite3_reset(compiledStatement);
Via iphonesdkarticles.com.
This will resolve your error.
-(BOOL) someUpdateFunction {
BOOL updatedSuccessfully = NO;
// Open the database.
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *updateQuery = [[NSString alloc] initWithFormat:#"UPDATE people SET user = 'terror' WHERE user = 'greg'"];
const char *query = [updateQuery UTF8String];
[updateQuery release];
sqlite3_stmt *statement;
int res = (sqlite3_prepare_v2( database, query, -1, &statement, NULL));
if(res == SQLITE_OK) {
int result = sqlite3_step(statement);
if(result == SQLITE_DONE) {
updatedSuccessfully = YES;
sqlite3_finalize(statement);
}else {
NSLog(#"Failed with error code: %d", result);
}
}else {
NSLog(#"Failed to prepare the update query with error code: %d", res);
}
}else {
NSLog(#"Failed to open the database");
}
sqlite3_close(database);
//NSLog(updatedSuccessfully);
//NSLog(#"The value of the bool is %#\n", updatedSuccessfully);
return updatedSuccessfully;
}
I was supplied this in the chat room. Thanks lads.
Remember to copy the DB over to the device else. You can find the DB path with this code:
- (NSString *) dataFilePath:(NSString *) dbName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:dbName];
return dbPath;
}
-(BOOL)buildtheDB{
BOOL updatedSuccessfully = NO;
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
NSString *sqlFile =[documentDirectory stringByAppendingPathComponent:kDatabaseFileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:sqlFile] == NO) {
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"database" ofType:#"sqlite"];
NSError *error = nil;
BOOL databaseCopied = [[NSFileManager defaultManager] copyItemAtPath:bundleSql toPath:sqlFile error:&error];
if (databaseCopied == NO) {
if (error) {
NSLog(#"Could not copy database file with error: %#", [error localizedDescription]);
}
}else {
NSLog(#"Database copied successfully");
}
}
else{
NSLog(#"Database already copied");
}
return updatedSuccessfully;
}

Update statement not working properly [duplicate]

I'm having trouble updating my database. I believe it's due to it possibly being read only, however I am unsure. I created my database in my console, and the code below adds the database to the project folder rather than referencing it externally. Here is the code to transfer the file to the project folder
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
databaseName = #"databasenew.sql";
/* copy over to phone code */
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
NSString *sqlFile =[documentDirectory stringByAppendingPathComponent:#"databasenew.sql"];
if (![[NSFileManager defaultManager] fileExistsAtPath:sqlFile]) {
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
NSError *error = nil;
[[NSFileManager defaultManager] copyItemAtPath:bundleSql toPath:sqlFile error:&error];
if (error) {
NSLog(#"Could not copy json file: %#", error);
}
else{
NSLog(#"yea");
}
}
else{
NSLog(#"transfer complete");
}
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
databasePath = bundleSql;
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
Here is the code where I try to update
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"Message"])
{
NSLog(soapResults);
NSString *convertString = soapResults;
check = [convertString intValue];
NSLog(#"user is");
NSLog(user);
if(check > 0){
databaseName = #"databasenew.sql";
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
databasePath = bundleSql;
sqlite3 *database;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "UPDATE people set user = 'munch'";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
NSLog(#"success");
NSLog(soapResults);
BOOL success = sqlite3_step(compiledStatement);
if (success != SQLITE_DONE) {
BOOL myBool=YES;
NSLog([NSString stringWithFormat:#"My Bool value : %d",success]);
}
}else{
NSLog(#"the fail ispreparing something");
NSAssert1(0, #"Error while creating update statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_finalize(compiledStatement);
}else{
NSLog(#"fail");
}
sqlite3_close(database);
NSString *string = [NSString stringWithFormat:#"%d", check];
NSLog(string);
NSLog(#"lolololol");
check = 0;
[self Bootup];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Problem!" message:#"Incorrect Username or Password"
delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:#"Yes", nil];
[alert show];
[alert release];
}
// gotoContent = checkConfirm;
}
if( [elementName isEqualToString:#"ValidateUserResponse"])
{
if(!soapResults)
{
soapResults = [[NSMutableString alloc] init];
NSLog(soapResults);
NSLog(#"above is soap validate user");
}
recordResults = TRUE;
}
}
I've done my NDlog debugging and it says "success" as it should if the code for updating is successful, however the database itself does not update. What is the reason for this?
You are forgeting some code for update statement
//the binding part is missing in your code , you need to write after Prepare statement.
sqlite3_bind_text(compiledStatement, 1, [string UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(compiledStatement))
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
sqlite3_reset(compiledStatement);
Via iphonesdkarticles.com.
This will resolve your error.
-(BOOL) someUpdateFunction {
BOOL updatedSuccessfully = NO;
// Open the database.
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *updateQuery = [[NSString alloc] initWithFormat:#"UPDATE people SET user = 'terror' WHERE user = 'greg'"];
const char *query = [updateQuery UTF8String];
[updateQuery release];
sqlite3_stmt *statement;
int res = (sqlite3_prepare_v2( database, query, -1, &statement, NULL));
if(res == SQLITE_OK) {
int result = sqlite3_step(statement);
if(result == SQLITE_DONE) {
updatedSuccessfully = YES;
sqlite3_finalize(statement);
}else {
NSLog(#"Failed with error code: %d", result);
}
}else {
NSLog(#"Failed to prepare the update query with error code: %d", res);
}
}else {
NSLog(#"Failed to open the database");
}
sqlite3_close(database);
//NSLog(updatedSuccessfully);
//NSLog(#"The value of the bool is %#\n", updatedSuccessfully);
return updatedSuccessfully;
}
I was supplied this in the chat room. Thanks lads.
Remember to copy the DB over to the device else. You can find the DB path with this code:
- (NSString *) dataFilePath:(NSString *) dbName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:dbName];
return dbPath;
}
-(BOOL)buildtheDB{
BOOL updatedSuccessfully = NO;
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
NSString *sqlFile =[documentDirectory stringByAppendingPathComponent:kDatabaseFileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:sqlFile] == NO) {
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"database" ofType:#"sqlite"];
NSError *error = nil;
BOOL databaseCopied = [[NSFileManager defaultManager] copyItemAtPath:bundleSql toPath:sqlFile error:&error];
if (databaseCopied == NO) {
if (error) {
NSLog(#"Could not copy database file with error: %#", [error localizedDescription]);
}
}else {
NSLog(#"Database copied successfully");
}
}
else{
NSLog(#"Database already copied");
}
return updatedSuccessfully;
}

sqlite database not updating modified data in iphone sdk

Well i am new to iphone coding and using sqlite in one of my application the problem is my sqlite database does not updates the modified data, i am following a sqlite based tutorial:
this is what i am doing:-
- (void) saveAllData {
if(isDirty) {
if(updateStmt == nil) {
const char *sql = "update Work Set Engagement = ?, Status = ?, Where WorkID = ?";
if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating update statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_text(updateStmt, 1, [Engagement UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 2, [Status UTF8String], -1, SQLITE_TRANSIENT);
//sqlite3_bind_double(updateStmt, 2, [Status doubleValue]);
sqlite3_bind_int(updateStmt, 3, WorkID);
//int Success = sqlit3_step(updateStmt);
if(SQLITE_DONE != sqlite3_step(updateStmt))
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
sqlite3_finalize(updateStmt);
isDirty = NO;
}
i am using :
- (IBAction) save_Clicked:(id)sender {
//Update the value.
//Invokes the set<key> method defined in the Work Class.
[objectToEdit setValue:txtField.text forKey:self.keyOfTheFieldToEdit];
[self.navigationController popViewControllerAnimated:YES];
}
for save button click and :
- (void) setEngagement:(NSString *)newValue {
self.isDirty = YES;
[Engagement release];
Engagement = [newValue copy];
}
- (void) setStatus:(NSString *)newNumber {
self.isDirty = YES;
[Status release];
Status = [newNumber copy];
}
for setting values, i banged my head thousand times and can not find what i am doing wrong can some body plz help me with this.....
this is the code for my getDBPath implementation
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"CheckList.sqlite"];
}
this code for my Data Base :
- (void) copyDatabaseIfNeeded {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"CheckList.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
Your code doesn't show opening the database, but I'm guessing you're opening one that is included in your app bundle? If so, you'll first need to copy the database into your app's Documents directory, because the application bundle is read-only.
You can get the path to the Documents directory with this:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]