Reputation: 163
I am trying to create DB using Sqlite3 in my iOS application. If I create DB in a sub folder of documents dir, it is NOT creating DB, it is failing to open or create database. If I don't create DB in a subfolder, instead if i directly create it in document directory. It is creating it properly.
It is giving path as databasePath: "/var/mobile/Containers/Data/Application/986037DB-6FA0-4066-9977-C5D7A075C5E7/Documents/MailFolder/INBOX.db"
But it is failing at -> if (sqlite3_open(dbpath, &database) == SQLITE_OK)
–
Below is my code creating DB in a sub folder. Could someone correct me what is wrong here?
- (BOOL) createFolderMailDB :(NSString *) dbName {
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
//docsDir =[[dirPaths objectAtIndex:0] stringByAppendingPathComponent:@"MailFolder"];
NSString *documentsPath = [dirPaths objectAtIndex:0];
docsDir = [documentsPath stringByAppendingPathComponent:@"/MailFolder"];
//docsDir = dirPaths[0];
// Build the path to the database file
NSMutableString *finalDBPath = [[NSMutableString alloc]init];
[finalDBPath appendString:dbName];
[finalDBPath appendString:@".db"];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: finalDBPath]];
NSLog(@"databasePath: %@", databasePath);
BOOL isSuccess = YES;
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "create table if not exists MailFolderDBTable (emailid text, foldername text, messagedata text)";
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
isSuccess = NO;
NSLog(@"Failed to create table");
}
sqlite3_close(database);
return isSuccess;
}
else {
isSuccess = NO;
NSLog(@"Failed to open/create database");
}
}
return isSuccess;
}
Upvotes: 1
Views: 1173
Reputation: 438467
The folder in which you are placing this database must exist or else attempts to create database there will fail. So create that folder before proceeding with the creation of the database:
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *databaseFolder = [documentsPath stringByAppendingPathComponent:@"MailFolder"];
NSFileManager *filemgr = [NSFileManager defaultManager];
if (![filemgr fileExistsAtPath:databaseFolder]) {
NSError *error;
if (![filemgr createDirectoryAtPath:databaseFolder withIntermediateDirectories:FALSE attributes:nil error:&error]) {
NSLog(@"Error creating %@: %@", databaseFolder, error);
}
}
NSString *databasePath = [[databaseFolder stringByAppendingPathComponent:dbName] stringByAppendingPathExtension:@"db"];
if (![filemgr fileExistsAtPath:databasePath]) {
// database creation logic
}
Upvotes: 4