2

在 SQLite Swift文档中有直接获取语句结果的参考。我准备了很多 SQL 查询,我真的不想重构它们。我会尽快使用它们,因为它们正在使用 db.prepare,如下所示。

带有结果的语句可能会被迭代。

let stmt = try db.prepare("SELECT id, email FROM users")
for row in stmt {
    print("id: \(row[0]), email: \(row[1])")
    // id: Optional(1), email: Optional("alice@mac.com")
}

返回值总是在它们周围有“Optional()”。有没有办法我们可以在没有这个的情况下获取原始行值?

4

3 回答 3

2

在变量之后使用!@stephenencelis 所说的解包值:

let stmt = try db.prepare("SELECT id, email FROM users")
for row in stmt {
    print("id: \(row[0]!), email: \(row[1]!)")
}
于 2015-11-16T20:34:51.113 回答
1

您可能想使用https://github.com/groue/GRDB.swift。它使您可以根据需要提取选项或非选项:

for row in Row.fetch(db, "SELECT id, email FROM users") {
    let id: Int64 = row.value(atIndex: 0)
    let email: String = row.value(atIndex: 1)
    print(id, email)
}
于 2015-11-24T18:06:28.163 回答
0

类型安全 API 允许您声明非可选类型的表达式,当从语句中拉回时,它们不会被包装。

从自述文件:

let users = Table("users")
let id = Expression<Int64>("id")
let name = Expression<String?>("name")
let email = Expression<String>("email")

try db.run(users.create { t in
    t.column(id, primaryKey: true)
    t.column(name)
    t.column(email, unique: true)
})
// CREATE TABLE "users" (
//     "id" INTEGER PRIMARY KEY NOT NULL,
//     "name" TEXT,
//     "email" TEXT NOT NULL UNIQUE
// )

let insert = users.insert(name <- "Alice", email <- "alice@mac.com")
let rowid = try db.run(insert)
// INSERT INTO "users" ("name", "email") VALUES ('Alice', 'alice@mac.com')

for user in db.prepare(users) {
    println("id: \(user[id]), name: \(user[name]), email: \(user[email])")
    // id: 1, name: Optional("Alice"), email: alice@mac.com
}

请注意,非可选的 和 都按原样返回idemail

于 2015-11-09T12:03:59.797 回答