GRDB 文档说:
一旦授予数据库连接,该execute
方法将执行不返回任何数据库行的 SQL 语句,例如 CREATE TABLE、INSERT、DELETE、ALTER 等。
所以如果你想获取行,你选择了错误的方法。
要获取行,请使用获取方法(以 开头fetch
),如“行查询”文档一章中所述,我鼓励您阅读该方法。
例如:
let rows = try dbQueue.inDatabase { db in
try Row.fetchAll(db, "SELECT * FROM games")
}
// Now we're back to the main thread: use rows:
for row in rows {
let name: String = row.value(named: "name")
let year: Int = row.value(named: "year")
print(name)
print(year)
}
这就是它“不通过模型”给出的。
然而模型仍然很方便:
let games = try dbQueue.inDatabase { db -> [Game] in
let rows = try Row.fetchAll(db, "SELECT * FROM games")
return rows.map { row in
Game(
name: row.value(named: "name"),
year: row.value(named: "year"))
}
}
// Now we're back to the main thread: use games
for game in games {
print(game.name)
print(game.year)
}
如果您的游戏类型(结构或类)采用 RowConvertible 协议,您甚至可以编写:
let games = try dbQueue.inDatabase { db in
try Game.fetchAll(db, "SELECT * FROM games")
}
如果 Game 也采用 TableMapping 协议,你会得到:
let games = try dbQueue.inDatabase { try Game.fetchAll($0) }
有关这些协议的文档,请参阅记录。