我有一个数据库,如果它不存在,我想向它添加一列。如何使用 sqlite.swift API 做到这一点?
问问题
3974 次
2 回答
8
通常,如果您要向现有表添加新列,您将需要一个迁移路径。您可以使用该userVersion
属性来管理数据库架构的版本:
if db.userVersion < 1 {
db.create(table: users) { t in
t.column(id, primaryKey: true)
t.column(email, unique: true)
}
db.userVersion = 1
}
if db.userVersion < 2 {
db.alter(table: users, add: name)
db.alter(table: users, add: age)
db.userVersion = 2
}
正如 Max 建议的那样,您还可以ifNotExists:
在以下create(table:…)
级别使用:
db.create(table: users, ifNotExists: true) { t in
t.column(id, primaryKey: true)
t.column(email, unique: true)
}
但是要添加新列,您必须解析一个笨拙的 PRAGMA 语句:
let tableInfo = Array(db.prepare("PRAGMA table_info(users)"))
if tableInfo.filter { col in col[1] == "name" } == nil {
db.alter(table: users, add: name)
}
if tableInfo.filter { col in col[1] == "age" } == nil {
db.alter(table: users, add: age)
}
几乎没有可读性(或推荐),但如果您正在处理旧数据库,则可能是必要的。
请务必阅读ALTER TABLE 文档以了解更复杂的更改。
于 2015-04-25T14:53:13.403 回答
3
swift 2.0 的正确方法如下:
let tableInfo = Array(db.prepare("PRAGMA table_info(users)"))
let foundColumn = tableInfo.filter {
col in col[1] as! String == "name"
}
if(foundColumn.count == 0){
try! db.run(users.addColumn(name))
}
于 2015-10-12T07:45:04.350 回答