Nivrutti Pawar
Nivrutti Pawar

Reputation: 524

How get table total count in Sqlite3 in swift4?

I am new in IOS and Sqlite3 DB.

What I want to achieve in sqlite3 DB and swift4 to get the total number count of table.

I Did the following steps.

func getTotalCount()->Int32{
    let queryStatementString = "SELECT COUNT(*) FROM Attendance"
    var stmt: OpaquePointer?

    print("select valid count \(queryStatementString) ")

    var totalCount: Int32 = 0
    var id: Int = 0

    if sqlite3_prepare_v2(db, queryStatementString, -1, &stmt, nil) == SQLITE_OK{
        if sqlite3_step(stmt) == SQLITE_ROW {
            id = Int(sqlite3_column_int(stmt, 0))
            print("id \(id)")
            totalCount = sqlite3_column_count(stmt!)
            print("db: validCount Result:")
            print("validCount \(totalCount)")

        }
    }

    if sqlite3_step(stmt) != SQLITE_DONE {
        let errmsg = String(cString: sqlite3_errmsg(stmt)!)
        print("db: failure getting punchTime: \(errmsg)")

    }

    return totalCount
}

But is always return me 1 as a count. I didn't get where I am missing.

Upvotes: 1

Views: 348

Answers (1)

Nivrutti Pawar
Nivrutti Pawar

Reputation: 524

I get an answer.

I am retrieving a wrong index value.

Refer below code.

func getTotalCount()->Int32{
    let queryStatementString = "SELECT COUNT(*) FROM Attendance"
    var stmt: OpaquePointer?
    var totalCount: Int32 = 0

    if sqlite3_prepare_v2(db, queryStatementString, -1, &stmt, nil) == SQLITE_OK{
        while sqlite3_step(stmt) == SQLITE_ROW {
            totalCount = sqlite3_column_int(stmt, 0)
            print("totalCount \(totalCount)")
        }
    }

    if sqlite3_step(stmt) != SQLITE_DONE {
        let errmsg = String(cString: sqlite3_errmsg(stmt)!)
        print("db: failure getting punchTime: \(errmsg)")
    }
    return totalCount
}

Upvotes: 1

Related Questions