Unnamed
Unnamed

Reputation: 1790

In my IOS app, how do I open create an sqlite3 database that I can use throughout my program?

I am trying to do this:

sqlite3 *db;
self.dbPath = "tasks.sqlite";
int result = sqlite3_open(self.dbPath, &db);

The code after this is is throwing errors. So I suspect that it is not working. What should I pass in as the path?

Upvotes: 1

Views: 201

Answers (1)

modusCell
modusCell

Reputation: 13429

NSString *strDatabaseName;
NSString *strDatabasePath;

-(void)getDatabase 
{
strDatabaseName = @"questionsdb.sqlite";    
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
strDatabasePath = [documentsDir stringByAppendingPathComponent:strDatabaseName];
}

-(BOOL) checkAndCreateDatabase {
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:strDatabasePath];
if(success) {
    return TRUE;
}
else {
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:strDatabaseName];
    [fileManager copyItemAtPath:databasePathFromApp toPath:strDatabasePath error:nil];
}
return FALSE;
}

then from any method

sqlite3 *database;
if(sqlite3_open([strDatabasePath UTF8String], &database) == SQLITE_OK) 
{
//doSomething
}

I hope it works for you as well. thank you.

Upvotes: 1

Related Questions