Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I get database path for creating database in iOS? I know how to execute queries but I want first create database from document directory.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
123 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try this

-(void)copyDatabaseIfNeeded
{
    @try
    {
        NSFileManager *fmgr=[NSFileManager defaultManager];
        NSError *error;
        NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        NSString *path=[paths objectAtIndex:0];
        dbPath=[path stringByAppendingPathComponent:@"Data.sqlite"];
        if(![fmgr fileExistsAtPath:dbPath]){
            NSString *defaultDBPath=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"Addict.sqlite"];
            if(![fmgr copyItemAtPath:defaultDBPath toPath:dbPath error:&error])
                NSLog(@"failure message----%@",[error localizedDescription]);
        }

    }
    @catch (NSException *exception)
    {
        NSLog(@"Exception: %@", exception);
    }

}

-(NSString *)getDBPath
{
    //Search for standard documents using NSSearchPathForDirectoriesInDomains
    //First Param = Searching the documents directory
    //Second Param = Searching the Users directory and not the System
    //Expand any tildes and identify home directories.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    return [documentsDir stringByAppendingPathComponent:@"Data.sqlite"];
}

-(void)openDatabase
{
    [self copyDatabaseIfNeeded];

    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
    {
        //Database Opened
        NSLog(@"Database opened");
    }
    else
    {
        NSLog(@"Database cannot be opened");
    }
}

-(void)closeDatabase
{
    sqlite3_close(database);
}

Hope it helps you..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...