gbenroscience
gbenroscience

Reputation: 1098

Select count(col_name) in sqlite (Swift) not working

I am using the sqlite wrapper here to access my sqlite database in Swift.

I wrote this code based on the wrapper to count the items on a table.

public func numberOfRows() -> Int {

        let cmd = """
        SELECT count(*) from  \(self.tableName)
        """

        do{

            let db = DatabaseUtils.getInstance().getConnection()


            let stmt = try db.prepare( cmd )


            if try stmt.step() == .row {
                return Int(from: stmt,index:  1) ?? -1
            }

            return -1

        }catch {
            Log.out("Error occurred while fetching count data in \(tableName)")
            return -1
        }

    }

But it keeps returning -1 as the logic instructs when the count is not found.

Every other thing works so far; create tables, inserts, batched inserts.

Also a select count(col_name) from table_name where some_col = "?" also works.

QUESTION:

How do I remedy it to work for

  SELECT count(*) from  table_name?

Upvotes: 1

Views: 245

Answers (1)

Rob
Rob

Reputation: 437622

The column numbers when returning values (e.g. the result of sqlite3_column_xxx) are zero-based. You’re attempting to retrieve column 1, when you meant column 0.


By the way, if you want to detect invalid index, you can remove that nil coalescing operator. E.g., so, instead of:

if try stmt.step() == .row {
    return Int(from: stmt,index:  1) ?? -1
}

You could instead check to see if not only if step succeeded, but also that Int(from:index:) returned a non-nil value:

if try stmt.step() == .row {
    if let count = Int(from: stmt, index: 1) {
        return count
    } else {
        // do whatever you want when it fails, e.g.

        fatalError("no value returned; invalid column index?")
    }
}

Or perhaps more succinctly:

if try stmt.step() == .row, let count = Int(from: stmt, index: 1) {
    return count
} else {
    fatalError("no value returned; invalid column index?")
}

That would lead you to recognize that you need the 0-based index:

if try stmt.step() == .row, let count = Int(from: stmt, index: 0) {
    return count
} else {
    fatalError("no value returned; invalid column index?")
}

Upvotes: 2

Related Questions