iossqlitefmdb

How can I read the whole row data from SQLite with FMDB in IOS dev?


I can read all column Data from code like this ...

FMResultSet *rs = [db executeQuery:@"SELECT Name, Age, FROM PersonList"];

while ([rs next]) {

NSString *name = [rs stringForColumn:@"Name"];

int age = [rs intForColumn:@"Age"];

}

or find some Data from this way

NSString *address = [db stringForQuery:@"SELECT Address FROM PersonList WHERE Name = ?",@"John"];

But if I want a Array contents the whole row's data(assume all my row data is a simple String)

How can I achieve that?


Solution

  • There is a resultDict method defined on the FMResultSet class. I would do it like this:

    FMResultSet *rs = [db executeQuery:@"SELECT Name, Age, FROM PersonList"];
    while ([rs next]) {
        NSLog(@"%@", [[rs resultDict] description]);
    }
    

    This should print something like:

    {
        Name = bbbbbird1;
        Age = 25;
    }
    

    for every row in the PersonList table. Now there are two ways of putting these values into the array. One is to use allValues method of NSDictionary, however the order of the columns will most probably be broken. The other way is to build the array yourself:

    FMResultSet *rs = [db executeQuery:@"SELECT Name, Age, FROM PersonList"];
    while ([rs next]) {
        NSMutableArray* rowData = [[NSMutableArray alloc] init];
        for(int i=0; i<[s columnCount]; i++) {
            [rowData addObject:[[rs resultDict] objectForKey:[[rs columnNameForIndex:i] lowercaseString]];
        }
        NSLog(@"%@", [rowData description]);
    }
    

    The above should print:

    (
        bbbbbird1,
        25
    )
    

    I hope this is what you are looking for. You can put this code in the FMResultsSet category if you need to have the rows as arrays in many places in you app.