4

Friends I Used FMDB and it is working very well, but i tryed to select single row but it is gives me an error

this is code

FMResultSet *fResult= [db executeQuery:@"SELECT * FROM contents WHERE id = 1"];
[fResult next];
NSLog(@"%@",[fResult stringForColumn:@"title"]);

Thank you

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • What data type is your id column? – Sammio2 Apr 06 '14 at 14:22
  • it is text. i do not want to use while or any loop, just i want to select only single row –  Apr 06 '14 at 14:26
  • You report that you received an error: What was that error message? We cannot help you if you don't tell us what the error was. – Rob Apr 06 '14 at 14:33

2 Answers2

3

You should check your results. For example:

FMResultSet *rs = [db executeQuery:@"SELECT * FROM contents WHERE id = 1"];

if (!rs) {
    NSLog(@"%s: executeQuery failed: %@", __FUNCTION__, [db lastErrorMessage]);
    return;
}

if ([rs next]) {
    NSString *title = [rs stringForColumn:@"title"];
    NSLog(@"title = %@", title);
} else {
    NSLog(@"%s: No record found", __FUNCTION__);
}

[rs close];

You are flying blind if you don't (a) check the executeQuery return code; and (b) if it failed, examine lastErrorMessage so you know why it didn't work.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Just wondering if all these have to be enclosed in `FMDatabaseQueue` for thread safety including operations like `insert` etc., – esh Feb 26 '15 at 16:43
  • Yes, if you're interacting with your database from multiple threads, then one would use `FMDatabaseQueue` to coordinate those various database requests. There's a lot more to writing thread-safe code than that, but that's beyond the scope of this particular question. – Rob Feb 26 '15 at 16:59
1

Can you try this ?

NSString *databasePath = [[NSBundle mainBundle] pathForResource:DBName ofType:@"sqlite"];
FMDatabase *db = [FMDatabase databaseWithPath:databasePath];

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

FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:databasePath];

[queue inDatabase:^(FMDatabase *db) {

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

    while ([results next]) {

        NSString *str = [results stringForColumn:@"your_column_name"];
    }
    [results close];
}];

[db close];
Erhan
  • 908
  • 8
  • 19
  • Thank you but i do not want While or any loop. i want to only single row like: WHERE id = 55; –  Apr 06 '14 at 14:17
  • if the results count is even only one item, you can use above code. – Erhan Apr 06 '14 at 14:18
  • @kakkuk If you don't want `while` loop, you can do `if ([results next]) {...}` and otherwise the code sample is the same. The key point, though, is that you always should check the result of your FMDB calls (e.g., don't just call `[results next]` without checking to see if it was successful). – Rob Apr 06 '14 at 14:24