从 SQLite.swift 中具有正确绑定的任意 SQL 语句获取结果

Getting results from arbitrary SQL statements with correct binding in SQLite.swift

SQLite.swift documentation说的是执行任意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? 类型,我不知道如何将其转换为我需要的类型。我看到 source code 中有一个 Statement.bind 方法,但我仍然没有发现如何应用它。

您可以从 table 中检索正确键入的选定列,如下所示:

// 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 值 到正确的类型:

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)
    }
}