如何在添加列之前检查列是否存在

时间:2015-04-23 15:33:25

标签: sqlite.swift

我有一个数据库,如果它不存在,我想添加一个列。 我如何使用sqlite.swift API做到这一点?

2 个答案:

答案 0 :(得分:8)

通常,如果要向现有表添加新列,则需要具有迁移路径。您可以使用git revert -m 1 D 属性来管理数据库模式的版本:

userVersion

您也可以按照Max的建议,在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 } 级别使用ifNotExists:

create(table:…)

但是为了添加新列,你必须解析一个笨拙的PRAGMA语句:

 db.create(table: users, ifNotExists: true) { t in
    t.column(id, primaryKey: true)
    t.column(email, unique: true)
 }

不太可读(或推荐),但如果您正在处理遗留数据库,可能是必要的。

请务必阅读the ALTER TABLE documentation以了解更复杂的更改。

答案 1 :(得分: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))
}