views:

689

answers:

1

hi people!

well, I have problems with my queries,i dont know why!! please help

i try to select an id from a table named moneda and I give the name like parameter,

this is my method with my query :

-(int)ConsultaIdMoneda:(NSString*) nombreMonedaParametro
{
    int idMonedaObtenido;
    NSLog(@" entre a consultar id de la moneda desde el app delegate");
    sqlite3 *database;

    const char *path = [[[NSBundle mainBundle] pathForResource:@"database2" ofType:@"sqlite"] UTF8String];
    if(sqlite3_open(path, &database) == SQLITE_OK)  
    {
     const char *sqlStatement =[[NSString stringWithFormat:@"Select idMoneda from moneda Where nombre = %@",nombreMonedaParametro] cStringUsingEncoding:NSUTF8StringEncoding];

     NSLog(@"%s",sqlStatement);
     sqlite3_stmt *compiledStatement;
     NSInteger result = sqlite3_prepare_v2(database,sqlStatement, -1, &compiledStatement, NULL);
     NSLog(@"%s",sqlStatement);
     if(result == SQLITE_OK) 
     {
      idMonedaObtenido = [[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)] intValue];
     }
     else
     {
      NSAssert1(0, @"Error . '%s'", sqlite3_errmsg(database));   
     }
     sqlite3_reset(compiledStatement);
     sqlite3_finalize(compiledStatement);
    }

    sqlite3_close(database);
    return idMonedaObtenido;     
}

and this is the error:

2009-12-03 00:28:45.715 BCDTravel[1220:20b] *** Assertion failure in -[BCDTravelAppDelegate ConsultaIdMoneda:], /Users/Mely/Desktop/BCDTravel version 45/Bcd/Classes/BCDTravelAppDelegate.m:101
2009-12-03 00:28:45.717 BCDTravel[1220:20b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error haciendo el select. 'no such column: euros''

i think the problem is in this line but i dont know how to slove suggestions pleasee!!

const char *sqlStatement =[[NSString stringWithFormat:@"Select idMoneda from moneda Where nombre = %@",nombreMonedaParametro] cStringUsingEncoding:NSUTF8StringEncoding];
+1  A: 

Because you are passing a character value you need to put quotes around the parameter in the SQL.

For example:

SELECT idMoneda
FROM   moneda
WHERE  nombre = '%@'

Otherwise, when the SQL is compiled, the value you pass in is itself treated as a column name (euros) instead of a candidate value of the nombre column.

Suggest you look into using prepared statements rather than assembling the string 'manually'. See this related SO question.

martin clayton
+1 for suggesting prepared statements. OP should look into the `sqlite3_bind_*` functions.
jensgram
thanks :) that works! this is what i did: const char *sqlStatement = [[NSString stringWithFormat:@"select idMoneda from moneda Where nombre = '%@'",nombreMonedaParametro] cStringUsingEncoding:NSUTF8StringEncoding];
babyDeveloper