【问题标题】:Getting results from arbitrary SQL statements with correct binding in SQLite.swift从 SQLite.swift 中正确绑定的任意 SQL 语句中获取结果
【发布时间】:2016-08-16 08:15:52
【问题描述】:

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 方法,但我仍然没有发现如何应用它。

【问题讨论】:

  • 您是否尝试过使用Expression,(例如let myInt: Expression<Int64> = ...
  • @l'L'l,好主意。不幸的是,它给出了同样的错误(无法将Binding? 转换为Expression<Int64>)。我过去曾成功使用过Expression,但现在我试图让任意 SQL 工作(因为this 的问题),我遇到了很多麻烦。

标签: swift sqlite sqlite.swift


【解决方案1】:

您可以从这样的表中检索正确键入的选定列:

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

【讨论】:

  • 您回答的第二部分解决了我的问题。您的答案的第一部分对于标准情况肯定更好(我以前也这样做过),但我特别想知道在执行任意 SQL 时如何做到这一点。 (我稍微更新了我的问题以反映这一点。)我诉诸任意 SQL 的原因是因为this as of yet unsolved problem
  • 在任意 SQL 查询后访问行数据时,有没有办法使用Expression 绑定列名?当我忘记更新硬编码的列索引号时,我可以看到将来会出现错误。
  • @Suragch:我对此表示怀疑。这需要分析查询字符串。
猜你喜欢
  • 2011-02-26
  • 2014-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多