Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios - open sqlite database

Tags:

sqlite

xcode

ios

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");
    }
like image 964
Ashish Agarwal Avatar asked Dec 05 '22 15:12

Ashish Agarwal


1 Answers

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;
}
like image 78
Andreas Avatar answered Dec 29 '22 03:12

Andreas