Thursday, 8 October 2015

DataBase Functions in iOS

Copy the database form resource folder to Document floder


- (void)copyAndInitialiseDatabase{
    sqlite3 *database;
    NSString *documentDBPath = [NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),@"DataBaseName"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:documentDBPath] == NO){
        NSString *resourceDBPath = [[NSBundle mainBundle] pathForResource:@"DataBaseName" ofType:@"sqlite"];
        if (resourceDBPath == nil){
            //NSLog(@" %s : %d : %s dabase is not found in resource folder. Please check the name of database or copy in resource folder.",__FILE__,__LINE__,__PRETTY_FUNCTION__);
            return;
        }
        [[NSFileManager defaultManager] copyItemAtPath:resourceDBPath toPath:documentDBPath error:nil];
    }
   
    // database is copied, open the database
    if (sqlite3_open_v2([documentDBPath  UTF8String], &database, SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK){
        // database is opend successfully.
    }else{
        // if fail to open, closing to cleanup the resouces
        sqlite3_close(database);
        //NSLog(@" %s: %d: %s fail to open the database. error == %s",__FILE__,__LINE__,__PRETTY_FUNCTION__,sqlite3_errmsg(database));
    }
}

No comments:

Post a Comment