0
votes

I am creating and iphone app using XCode 4.2. And I am using sqlite3 database for the app. I created and ran the app successfully on iPhone 3GS and with XCode 3.2.5, when I am having a problem with the XCode 4.2. The db file cannot open, here is the sample code code for opening the Table. And when I opened the same db file using SQlite manager, I could see the table. I don't understand what the error is.

static sqlite3 *database = nil;
static sqlite3_stmt *selectStmt = nil;

+ (void) getInitialDataToDisplay:(NSString *)dbPath {
    NSLog(@"Path: %@",dbPath);
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
        NSString *sqlStr = @"select * from Space";
        const char *sql = [sqlStr UTF8String];
        sqlite3_stmt *selectstmt;
        if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
            while(sqlite3_step(selectstmt) == SQLITE_ROW) {
                NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
                SpaceClass *spaceObj = [[SpaceClass alloc] initWithPrimaryKey:primaryKey];
                spaceObj.spacePK = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
                spaceObj.spName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
                spaceObj.spDescrptn = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];               
                [appDelegate.spaceArray addObject:spaceObj];
                [spaceObj release];
            }
        }else
            NSLog(@"not ok");
    }
    else
        sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}

Please help, thanks

1
Can you check what does NSLog(@"Error=%s",sqlite3_errmsg(&db)) give? - iNoob

1 Answers

2
votes

You put the close method in the wrong place I think. I have been using SQLite3 in iOS for 2 weeks and I had that problem. I solved it by putting the SQLite3_close method in the last line of the if(open == ok).

Your code should look like:

if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{       
    if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) 
    {
        while(sqlite3_step(selectstmt) == SQLITE_ROW) 
        {

        }
    } 
    else
    {
        NSLog(@"not ok");
    }
    //here you should close database, before exit from if open block
    sqlite3_close(database);
}
else
{
    //here is not needed because of database open failure
    //sqlite3_close(database);
    NSLog(@"not ok");
}

This should solve your problem because now you're going to close the database each time you open it. But in your code you open it time after time without close it!