I am trying to create a class to abstract my SQLite methods from my business logic etc. However, I can’t seem to ever access my database because it appears as if it is never being created. Please see the code below. I open the database at the specified path. Then I close it later on. After the close, I use the terminal to inspect my Documents directory (within the app). At this point there is no file where I specified it. Does it only create the file when I insert data to the database? Or am I not properly creating the database?
#import "SQLController.h"
@implementation SQLController
@synthesize database;
-(id)initWithDefaultDB {
return [self initWithDBPath:[self dbFilePath]];
}
-(id)initWithDBPath:(NSString *)dbPath {
self = [super init];
if(self) {
sqlite3 *db;
const char *dbPathCString = [dbPath UTF8String];
int result = sqlite3_open(dbPath, &db);
if (result != SQLITE_OK) {
NSString *errorTag = @"Failed to open database at ";
NSString *errorMessage = [errorTag stringByAppendingString:dbPath];
NSLog(errorMessage);
sqlite3_close(db);
} else {
const char *createQuery = "CREATE TABLE IF NOT EXISTS items (title TEXT, details TEXT, category TEXT);";
self.database = db;
char *error;
if (sqlite3_exec(self.database, createQuery, NULL, NULL, &error) != SQLITE_OK) {
sqlite3_close(self.database);
NSLog(@"Failed to create table");
NSAssert(0,@"Error creating table: %s", error);
}
}
}
return self;
}
-(NSString *)dbFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"testdb.sqlite"];
}
@end
Do you ever write to the DB before closing it? Sqlite is lazy – it doesn’t create the DB until first write.
Another thing to look at is your creating the C string (dbPathCString) but not passing it into open (you’re passing dbPath).