Idan Moshe
Idan Moshe

Reputation: 1535

Select 2 columns from table, query in one

In android I wrote this code:

public Trap getCloseTrap() 
    {   
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();      
        Cursor cur = db.query(TRAP_TABLE, null, null, null, null, null, DISTANCE_TO_CLOSE_POINT+" ASC LIMIT 1");
        Trap closeTrap = readFromCursor(cur);
        cur.close();
        return closeTrap;
    }

In objective-c I tried to do something similar, this way:

- (Traps*)getCloseTrap
{
    Traps *aTrap = [[Traps alloc] init];
    // SELECT * FROM traps_table ORDER BY dist_to_close_point ASC LIMIT 1
    NSString *sqlStatment = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY %@ ASC LIMIT 1", TRAP_TABLE, DISTANCE_TO_CLOSE_POINT];
    FMResultSet *query = [db executeQuery:sqlStatment];
    while ([query next]) {
        int trapID = [query intForColumn:ID];
        aTrap = [self getTrap_trapID:trapID];
    }
    return aTrap;
}

I didn't tested it yet but I know I've something wrong in here with my objective-c code.

EDIT:

Fixed my code plus using FMDB now.

Upvotes: 0

Views: 137

Answers (1)

laalto
laalto

Reputation: 152817

  1. You're missing ORDER BY <column_name> from the SQL. In Android, the query builder adds ORDER BY for you but with raw SQL you'll have to do it yourself.

  2. sqlite3_prepare_v2() compiles the SQL but doesn't run it. Use sqlite3_step() to run the compiled query. This is the same as cursor moveTo...() in Android.

Upvotes: 1

Related Questions