在SQLite.swift中从具有正确绑定的任意SQL语句获取结果 [英] Getting results from arbitrary SQL statements with correct binding in SQLite.swift
本文介绍了在SQLite.swift中从具有正确绑定的任意SQL语句获取结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
SQLite.swift文档关于执行任意SQL:
The SQLite.swift documentation says about executing arbitrary SQL:
let stmt = try db.prepare("SELECT id, email FROM users")
for row in stmt {
for (index, name) in stmt.columnNames.enumerate() {
print ("\(name)=\(row[index]!)")
// id: Optional(1), email: Optional("alice@mac.com")
}
}
我想像这样直接获取值
let stmt = try db.prepare("SELECT id, email FROM users")
for row in stmt {
let myInt: Int64 = row[0] // error: Cannot convert value of type 'Binding?' to specified type 'Int64'
let myString: String = row[1] // error: Cannot convert value of type 'Binding?' to specified type 'String'
}
,但行索引的类型为Binding?
,我不知道如何将其转换为所需的类型.我看到源代码中有一个Statement.bind
方法,但是我仍然没有发现如何应用它.
but the row index is of type Binding?
and I can't figure out how to convert that to the type I need. I see there is a Statement.bind
method in the source code but I am still not discovering how to apply it.
推荐答案
您可以从像这样的表中检索正确键入的所选列:
You can retrieve correctly typed selected columns from a table like this:
// The database.
let db = try Connection(...)
// The table.
let users = Table("users")
// Typed column expressions.
let id = Expression<Int64>("id")
let email = Expression<String>("email")
// The query: "SELECT id, email FROM users"
for user in try db.prepare(users.select(id, email)) {
let id = user[id] // Int64
let mail = user[email] // String
print(id, mail)
}
一种替代方法是(可选)强制转换Binding
值
正确的类型:
An alternative is to (optionally) cast the Binding
values
to the correct type:
let stmt = try db.prepare("SELECT id, email FROM users")
for row in stmt {
if let id = row[0] as? Int64,
let mail = row[1] as? String {
print(id, mail)
}
}
这篇关于在SQLite.swift中从具有正确绑定的任意SQL语句获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文