I am trying to read data from a sqlite database and display it in a table view in an ios app. But I am not able to open the sqlite database for some reason and the app crashes with the message - Failed to open database.
I created the database using the Firefox sqlite manager and copied the file into the Xcode project.
Here's my code -
-(NSString *)dataFilePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:kFilename];
}
I am trying to open the database using the sqlite3_open_v2 command inside the viewDidLoad
sqlite3 *database;
if (sqlite3_open_v2([[self dataFilePath] UTF8String], &database, SQLITE_OPEN_READWRITE, NULL) != SQLITE_OK) {
sqlite3_close(database); // not sure you need to close if the open failed
NSAssert(0, @"Failed to open database");
}
This is how I open my database. I have not been doing SQLite for a long time and I am not able to give you much help, other than providing this code that I use in my own application. This is from a class that I use in my app.
static sqlite3 *database;
static sqlite3_stmt *enableForeignKey;
@implementation DBAdapter
+ (sqlite3 *)sharedInstance {
if (database == NULL) {
sqlite3 *newDBconnection;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"klb_db.sqlite"];
if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {
//NSLog(@"Database Successfully Opened :)");
database = newDBconnection;
if (sqlite3_prepare_v2(database, "PRAGMA foreign_keys = ON", -1, &enableForeignKey, NULL) != SQLITE_OK) {
NSLog(@"ERROR IN PRAGMA!");
}
sqlite3_finalize(enableForeignKey);
} else {
NSLog(@"Error in opening database :(");
database = NULL;
}
}
return database;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With