FMDB SQLite question: row count of a query?

前端 未结 8 2029
别那么骄傲
别那么骄傲 2021-02-01 17:41

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

相关标签:
8条回答
  • 2021-02-01 18:16

    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?

    0 讨论(0)
  • 2021-02-01 18:16

    updated for Swift 3 minor change to "int For Column"

    if let rs = db.executeQuery("SELECT COUNT(*) as Count FROM TABLE_NAME", withArgumentsInArray: nil) {
    while rs.next() {
        print("Total Records:", rs.int(forColumn: "Count"))
        }
    }
    
    0 讨论(0)
  • 2021-02-01 18:20

    The first one is also right but by using this method you can retrieve records and count using the same query , no headache to write another one. Just add count(*) as count to your query.

    You could always just run the proper SQL statement. I do something like:

    FMResultSet *rs = [database executeQuery:@"select count(*) as count from words"];
    [rs next];
    
    wordsThatExist = [rs intForColumn:@"count"];
    

    Setting up the SQL query may be quicker and cheaper then iterating.. I believe counts are cheap.

    0 讨论(0)
  • 2021-02-01 18:23

    updated for Swift 4 minor change in method parameter name

    if let rs = db.executeQuery("SELECT COUNT(*) as Count FROM TABLE_NAME", withArgumentsIn: nil) {
    while rs.next() {
        print("Total Records:", rs.int(forColumn: "Count"))
        }
    }
    
    0 讨论(0)
  • 2021-02-01 18:31

    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:.

    0 讨论(0)
  • 2021-02-01 18:32

    Please Try Following Code, this works for me

    let objManager = ModelManager.getInstance()
    
    objManager.database?.open()
    
    let resultSet1: FMResultSet! = sharedInstance.database!.executeQuery("SELECT COUNT(Field) FROM TableName”, withArgumentsInArray:nil)
    
            if (resultSet1 != nil)
            {
                while resultSet1.next()
                {
                  countRecord = Int(resultSet1.intForColumn("COUNT(Field)"))
                }
    
            }
    
         print(countRecord)
    

    You Will get Count of Field

    0 讨论(0)
提交回复
热议问题