0

I want to get number of rows in result set. I am using FMDB for database operations. There is also one function hasAnotherRow() but it returns true everytime. Below is my code.

let selectQuery = "SELECT * FROM \(tableName) WHERE chrSync = 'Y'"
if let rs = database.executeQuery(selectQuery, withArgumentsIn: [])
{

    // Here I want to check if rs has more than 0 rows

    while(rs.next()){
        let dir = rs.resultDictionary                 
        let json = JSON(dir)
        data.append(json)

        print("Has another: \(rs.hasAnotherRow())") // It always returns true   
    }
    let json = JSON(data)
    return json
}

I am new in IOS, so please share me link if is there already answered.

Thanks.

Sagar Zala
  • 4,854
  • 9
  • 34
  • 62
  • @Anbu.Karthik, I don't want only count from Query. I wants size of result set with data. – Sagar Zala Mar 29 '19 at 11:44
  • 1
    Many times you can't get the count since that is a query in itself and also because the result set might not have all rows (for memory reasons) and fetches the next row from the database every time you call `next()` and thus it doesn't know. I don't know fmdb and how it implements the result set handling but most likely you need to count the number of rows manually. – Joakim Danielson Mar 29 '19 at 12:04
  • @JoakimDanielson, thanks for information. – Sagar Zala Mar 29 '19 at 12:29

1 Answers1

1

I think here is the key (https://github.com/aws-amplify/aws-sdk-ios/tree/master/AWSCore/FMDB):

You must always invoke -[FMResultSet next] before attempting to access the values returned in a query, even if you're only expecting one:

FMResultSet *s = [db executeQuery:@"SELECT COUNT(*) FROM myTable"];
if ([s next]) {
    int totalCount = [s intForColumnIndex:0];
}

Swift

var s: FMResultSet? = db.executeQuery("SELECT COUNT(*) FROM myTable", withArgumentsIn: nil)
if s?.next() != nil {
    var totalCount: Int? = s?.int(forColumnIndex: 0)
}

It can be used any SELECT, if the select returns rows then the last value for totalCount will have the number of rows in your FMResultSet.

abanet
  • 1,327
  • 17
  • 22