Powered By Blogger

Tuesday, October 12, 2010

How to retrieve records from table in iOS SDK?

+(NSMutableArray *)getAllColors
{
    sqlite3 *database = nil;
    sqlite3_stmt *stmt = nil;
    NSString *sql = nil;
    NSMutableArray *arrColors = [NSMutableArray array];
  
    NSInteger op_status = sqlite3_open([[ApplicationData returnDatabasePath] UTF8String], &database);
    @try
    {
        if (op_status==SQLITE_OK)
        {
            sql = [NSString stringWithFormat:@"select color_name,color_code from Color"];
            op_status = sqlite3_prepare(database, [sql UTF8String], -1, &stmt, nil);
            if (op_status==SQLITE_OK)
            {
                while (sqlite3_step(stmt)==SQLITE_ROW)
                {
                    Color *obj_color = [[Color alloc]init];
                    obj_color.color_name = [ApplicationData checkStringValue:stmt withColumnIndex:0];
                    obj_color.color_code = [ApplicationData checkStringValue:stmt withColumnIndex:1];
                    [arrColors addObject:obj_color];
                    [obj_color release];
                }
            }
            else
            {
                goto end_of_transaction;
            }
        }
    end_of_transaction:
        if (stmt!=nil) {
            sqlite3_finalize(stmt);
            stmt=nil;
        }
        if (database!=nil) {
            sqlite3_close(database);
            database=nil;
        }
        sql = nil;
    }
    @catch (NSException * e)
    {
        // thhrow exception
        if (stmt!=nil) {
            sqlite3_finalize(stmt);
            stmt=nil;
        }
        if (database!=nil) {
            sqlite3_close(database);
            database=nil;
        }
        sql = nil;
    }
    return arrColors;
}