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:osHow 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:osTry 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..