Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FMDB SQLite question: row count of a query?

does anyone know how to return the count of a query when using FMDB? If I executeQuery @"select count(*) from sometable were..." I get an empty FMResultSet back. How can I get the row count of the query? Do I need to do a query like "select * from sometable where.." and iterate through the result set? Or can I use useCount or whats the best way (in terms of performance) to do this?

Thanks!

like image 478
Fuggly Avatar asked Oct 01 '10 08:10

Fuggly


3 Answers

Shorter code to accomplish the same thing:

NSUInteger count = [db intForQuery:@"SELECT COUNT(field) FROM table_name"];

Make sure to include the FMDatabaseAdditions.h header file to use intForQuery:.

like image 88
Ben Baron Avatar answered Dec 19 '22 12:12

Ben Baron


try this. It works for me. Iterating all the records is not recommended.

FMResultSet *rs = [db executeQuery:@"select count(FIELD) as cnt from TABLENAME"];
while ([rs next]) {
    NSLog(@"Total Records :%d", [rs intForColumn:@"cnt"]);
}

May be you should check your Where clause.

like image 20
palaniraja Avatar answered Dec 19 '22 13:12

palaniraja


Swift 2 Example

This code snippet will print the count for you.

if let rs = db.executeQuery("SELECT COUNT(*) as Count FROM TABLE_NAME", withArgumentsInArray: nil) {
    while rs.next() {
        print("Total Records:", rs.intForColumn("Count"))
    }
}

If it did not work, a few suggestions:

a) Look for a line in your project that says let database = or var database =. If you find one then change db to database
b) Did you change the TABLE_NAME in the Select statement to whatever your table is called?

like image 36
rvg Avatar answered Dec 19 '22 13:12

rvg