在 sqlite (Swift) 中选择 count(col_name) 不起作用 [英] Select count(col_name) in sqlite (Swift) not working
问题描述
我正在使用 sqlite 包装器此处在 Swift 中访问我的 sqlite 数据库.
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
}
}
但是当找不到计数时,它会按照逻辑指示不断返回 -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.
还有一个 select count(col_name) from table_name where some_col = "?"
也有效.
问题:
我如何补救它以使其工作
How do I remedy it to work for
SELECT count(*) from table_name?
推荐答案
返回值时的列号(例如 sqlite3_column_xxx
) 从零开始.您正在尝试检索列 1
,而您的意思是列 0
.
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
.
顺便说一句,如果你想检测无效索引,你可以删除那个 nil
合并运算符.例如,所以,而不是:
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
}
您可以改为检查是否不仅 step
成功,而且 Int(from:index:)
返回非 nil
代码>值:
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?")
}
}
或者更简洁:
if try stmt.step() == .row, let count = Int(from: stmt, index: 1) {
return count
} else {
fatalError("no value returned; invalid column index?")
}
这会让您认识到您需要从 0 开始的索引:
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?")
}
这篇关于在 sqlite (Swift) 中选择 count(col_name) 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!