Mehmet63
Mehmet63

Reputation: 81

SQLite database not loading on iphone device

When I test my app on the simulator everything works. But when I test the app on my iPhone, it doesn't load from the db.sqlite3 data base.

I tried every solution from the internet. I cleaned the app. I added the database to the build phrases - copy bundle resources etc. Can you help me? Is there any fails in my coding?

-(void)openDataBase{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    dbPath = [documentsDirectory stringByAppendingString:@"db.sqlite3"];

    //load it
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *pathInRessource = [[NSBundle mainBundle] pathForResource:@"db" ofType:@"sqlite3"];

    //exist it?
    if (![fileManager fileExistsAtPath:dbPath]) {
        [fileManager copyItemAtPath:pathInRessource toPath:dbPath error:nil];
    }

    //open database
    int result = sqlite3_open([dbPath UTF8String], &db);
    if (result != SQLITE_OK) {
        sqlite3_close(db);

        return;
    }

    //if ok
    NSLog(@"Data base opened");

}

Upvotes: 1

Views: 752

Answers (2)

swiftBoy
swiftBoy

Reputation: 35783

I am wondring where you getting stuck, I am doing same way and its working fine to me.

BTW I have updated your code, how I am handling, please check let me know if find and trouble in this.

//My DB variable
static sqlite3 *database;

-(void)openDataBase{
if (database == NULL) 

    sqlite3 *mDatabse;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    dbPath = [documentsDirectory stringByAppendingString:@"db.sqlite3"];

    //load it
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *pathInRessource = [[NSBundle mainBundle] pathForResource:@"db" ofType:@"sqlite3"];

    //exist it?
    if (![fileManager fileExistsAtPath:dbPath]) {
        [fileManager copyItemAtPath:pathInRessource toPath:dbPath error:nil];
    }

    if (sqlite3_open([path UTF8String], &mDatabse) == SQLITE_OK) {   
            NSLog(@"Database Successfully Opened");
            database = mDatabse;


        } else {
            NSLog(@"Error in opening database");
            mDatabse = NULL;
        }

}

Upvotes: 1

Esha
Esha

Reputation: 1303

At the time of opening database you can call this with its else case to get the issue.

if (sqlite3_open([getDBPath UTF8String], &sqlhandle) == SQLITE_OK)
{
     NSLog(@"Database Open!");
}
else
{
    NSLog(@"Select err: %s",sqlite3_errmsg(sqlhandle));
}

You will be able to get proper error message using this

Upvotes: 2

Related Questions