eugui
eugui

Reputation: 471

update sqlite in iOS app

I'm new with xcode and i'm having problem to update a sqlite.

readBioViewController.h

@interface readBioViewController : UIViewController {
    NSString *fav;
}

readBioViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    fav = @"1";
}

- (IBAction)addFavorito:(id)sender {
    DataDAO *dbCrud = [[DataDAO alloc] init];
    NSLog(@"addFavorito favid '%@'.", fav);
    [dbCrud addFavorito:fav];
}

DataDAO.m

-(void)addFavorito:(NSString *)fav {

    NSFileManager *fileMgr = [NSFileManager defaultManager];

    NSString *dirPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"versos.sqlite"];

    BOOL success = [fileMgr fileExistsAtPath:dirPath];

    if(!success) {
        NSLog(@"Cannot locate database file '%@'.", dirPath);
    }

    if(!(sqlite3_open([dirPath UTF8String], &db) == SQLITE_OK)) {
        NSLog(@"An error has occured.");
    }

    NSString *sql = @"update Versos set favorito = 1 Where id = 2";

    char *err;
    if(sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
        sqlite3_close(db);
        NSLog(@"erro no update");
    } else
        NSLog(@"fez o update");
}

I have a button (IBOutlet - addFavorito) and I want to execute the sql to update ID (2). I see in the NSLog the result "NSLog(@"fez o update");" but when I open the versos.sqlite the result in ID 2 is favorito=0 and no favorito=1.

Upvotes: 0

Views: 714

Answers (2)

user1113101
user1113101

Reputation: 955

Use this function to create database in document directory.

-(void)CopyDatabaseIfNeeded
{

NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *dbpath=[paths objectAtIndex:0];

dbpath=[dbpath stringByAppendingPathComponent:@"versos.sqlite"];

BOOL success;

NSFileManager *filemanager=[NSFileManager defaultManager];

success=[filemanager fileExistsAtPath:dbpath];

if(success) return;

NSString *dbpathfromapp=[[[NSBundle mainBundle] resourcePath ]   stringByAppendingPathComponent:@"versos.sqlite"];
success=[filemanager copyItemAtPath:dbpathfromapp toPath:dbpath error:nil];
if(!success)
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Error " message:@"failed to Create writable dataBase" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    [alert show];
    [alert release];
}

}

and then for updating database, Use following function to get path of database/

-(NSString *) GetDatabasePath {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ;
NSString *documentsDirectory = [paths objectAtIndex:0] ;
return [documentsDirectory stringByAppendingPathComponent:@"versos.sqlite"] ;
}

Upvotes: 0

EricS
EricS

Reputation: 9768

You can't update the database because it's inside of your application bundle. You should copy the database to the Documents directory first and modify that file instead.

Upvotes: 2

Related Questions