Search This Blog

Thursday, 16 August 2012

How to Create a sqlite database programmatically in xcode 4.3 with storyboard

Hello Friends,
                      So still making those sqlite databases in some sqliteManager and copy them to device on first run.....do you ever think that made a duplicate database that is the one in you app ....and its useless as you app is using the one which is copied from app to device?? why making fuss and using memory uselessly??? ....here is the code to create database programmatically in xcode....


CODE:

In AppDelegate.h declare a NSString variable as follows:


@interface AppDelegate : UIResponder <UIApplicationDelegate>{
NSString *databasePath;
}
@property(retain,nonatomic)NSString *databasepath;


@end

In AppDelegate.m file do something like this:

@synthesize databasepath;



And the View where you want to create database do this:
- (void)viewDidLoad
{

  NSString *documentdir;
    NSArray *documentPaths;
    
    documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentdir = [documentPaths objectAtIndex:0];
    app.databasepath = [[NSString alloc]initWithString:[documentdir stringByAppendingPathComponent:@"favourites.db"]];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:app.databasepath]==NO){
        
        const char *defaultPath = [app.databasepath UTF8String];
        
        if(sqlite3_open(defaultPath, &database)==SQLITE_OK){
            char *errMsg;
            
            const char *create_Query = "CREATE TABLE IF NOT EXISTS FAVOURITESTATION(stationName TEXT,stationURL TEXT)";
            
            if(sqlite3_exec(database, create_Query, NULL, NULL, &errMsg)!=SQLITE_OK){
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"JUKEBOX" message:@"Failed to create Table." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
           
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"JUKEBOX" message:@"Failed to create Database." delegate:self cancelButtonTitle:@"OK"otherButtonTitles:nil, nil];
            
            [alert show];
        }
        fileManager = nil;
         sqlite3_close(database);
    }
}


Happy Programming...;) ask for any queries..




1 comment: