Search code examples
objective-ciosfmdb

FMDB to Read from Database for an iPhone Application


I am using the following code to read the records from the customers table. For some reason the resultset returned is always empty.

    -(NSMutableArray *) getCustomers
{
    NSMutableArray *customers = [[NSMutableArray alloc] init];

    NSString *databaseName = @"Customers.db";

    NSArray *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDir = [documentsPath objectAtIndex:0];

    NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

    FMDatabase *db = [FMDatabase databaseWithPath:databasePath];

    if(![db open]) 
    {
        return nil; 
    }

    FMResultSet *results = [db executeQuery:@"SELECT * FROM customers"];

    while([results next]) 
    {
        Customer *customer = [[Customer alloc] init];


        customer.firstName = [results stringForColumn:@"firstname"];
        customer.lastName = [results stringForColumn:@"lastname"];

        [customers addObject:customer];

    }

    [db close];

    return customers; 


}

I have checked in the database multiple times and it shows the data but for some reason the FMDB is not able to retrieve it!


Solution

  • set db log errors to true, this will show you log in console where you can find the problem.

    FMDatabase *db = [FMDatabase databaseWithPath:databasePath];
    db.logsErrors = YES;