我正在使用sqlite包装器here访问Swift中的sqlite数据库。
我基于包装程序编写了此代码,以对表中的项目进行计数。
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,如逻辑所示。
到目前为止,其他所有功能都可以正常工作;创建表,插入,批处理插入。
select count(col_name) from table_name where some_col = "?"
也可以。题:
我该如何补救才能工作
SELECT count(*) from table_name?
最佳答案
返回值时的列号(例如sqlite3_column_xxx
的结果)从零开始。当您要表示列1
时,您正在尝试检索列0
。
顺便说一句,如果要检测无效索引,可以删除该nil
合并运算符。例如,而不是:
if try stmt.step() == .row {
return Int(from: stmt,index: 1) ?? -1
}
相反,您可以检查是否不仅
step
成功,而且Int(from:index:)
返回了非nil
值: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开始的索引:
if try stmt.step() == .row, let count = Int(from: stmt, index: 0) {
return count
} else {
fatalError("no value returned; invalid column index?")
}
关于sql - 选择sqlite(Swift)中的count(col_name)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59118229/