sqlite.swift – 如何在添加列之前检查列是否存在
发布时间:2020-12-12 18:58:26 所属栏目:百科 来源:网络整理
导读:我有一个数据库,如果它不存在,我想添加一个列. 我如何使用sqlite. swift API做到这一点? 解决方法 通常,如果要向现有表添加新列,则需要具有迁移路径.您可以使用userVersion属性来管理数据库模式的版本: if db.userVersion 1 { db.create(table: users) { t
我有一个数据库,如果它不存在,我想添加一个列.
我如何使用sqlite. swift API做到这一点? 解决方法通常,如果要向现有表添加新列,则需要具有迁移路径.您可以使用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建议的那样,在create(table:…)级别使用ifNotExists: 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) } 不太可读(或推荐),但如果您正在处理遗留数据库,可能是必要的. 请务必阅读the ALTER TABLE documentation以了解更复杂的更改. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |