XCode sqlite3 - SELECT always return SQLITE_DONE

Posted by user573633 on Stack Overflow See other posts from Stack Overflow or by user573633
Published on 2011-01-13T03:40:59Z Indexed on 2011/01/13 3:54 UTC
Read the original article Hit count: 293

Filed under:
|
|

Hi developers.... a noob here asking for help after a day of head-banging....

I am working on an app with sqlite3 database with one database and two tables. I have now come to a step where I want to select from the table with an argument. The code is here:

-(NSMutableArray*) getGroupsPeopleWhoseGroupName:(NSString*)gn;{

 NSMutableArray *groupedPeopleArray = [[NSMutableArray alloc] init];

 const char *sql = "SELECT * FROM Contacts WHERE groupName='?'";

 @try { 
     NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);  
     NSString *docsDir = [paths objectAtIndex:0];  
     NSString *theDBPath = [docsDir stringByAppendingPathComponent:@"ContactBook.sqlite"];

     if (!(sqlite3_open([theDBPath UTF8String], &database) == SQLITE_OK))
     { NSLog(@"An error opening database."); }

     sqlite3_stmt *st;
     NSLog(@"debug004 - sqlite3_stmt success.");   

     if (sqlite3_prepare_v2(database, sql, -1, &st, NULL) != SQLITE_OK)
     { NSLog(@"Error, failed to prepare statement."); }

     //DB is ready for accessing, now start getting all the info.
     while (sqlite3_step(st) == SQLITE_ROW)
     {   

        MyContacts * aContact = [[MyContacts alloc] init];

        //get contactID from DB.
        aContact.contactID = sqlite3_column_int(st, 0);

        if (sqlite3_column_text(st, 1) != NULL)
        { aContact.firstName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(st, 1)]; }
        else { aContact.firstName = @""; }

        // here retrieve other columns data ....

       //store these info retrieved into the newly created array.
       [groupedPeopleArray addObject:aContact];

       [aContact release];

    }

    if(sqlite3_finalize(st) != SQLITE_OK)
    { NSLog(@"Failed to finalize data statement."); }

    if (sqlite3_close(database) != SQLITE_OK)
    { NSLog(@"Failed to close database."); }

    }

 @catch (NSException *e) {
 NSLog(@"An exception occurred: %@", [e reason]);
 return nil;  }

 return groupedPeopleArray;}

MyContacts is the class where I put up all the record variables.

My problem is sqlite3_step(st) always return SQLITE_DONE, so that it i can never get myContacts. (i verified this by checking the return value).

What am I doing wrong here?

Many thanks in advance!

© Stack Overflow or respective owner

Related posts about iphone

Related posts about xcode