我有一個數據庫,如果它不存在,我想添加一列。 如何使用sqlite.swift API來做到這一點?如何在添加列之前檢查列是否存在
4
A
回答
6
通常,如果要將新列添加到現有表中,您將希望具有遷移路徑。您可以使用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
}
還可以,麥克斯認爲,在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以瞭解更多複雜的更改。
2
爲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))
}
相關問題
- 1. Mysql腳本檢查列表是否存在或在表中添加列之前
- 2. 在使用功能添加新列表之前檢查列表是否存在?
- 3. 如何在將列添加到PL/SQL中的現有表之前檢查列是否存在?
- 4. 在繼續之前檢查文件列表是否存在?
- 5. 在更改表之前檢查列是否存在
- 6. Yii在創建之前檢查數據庫列是否存在
- 7. 添加之前檢查行是否存在?
- 8. 檢查是否存在散列,如果不存在,則添加散列
- 9. 如何在添加對象之前檢查對象是否已經存在?
- 10. 如何在添加之前檢查該元素是否已經存在?
- 11. 如何在調用它之前檢查數組/散列鍵是否存在?
- 12. 在創建列表之前檢查列表是否已經存在
- 13. 如何在asp.net中添加之前檢查列表框中是否已經存在一個值
- 14. 如何查看列是否存在? instanciate resultset對象之前?
- 15. 是否可以在視圖中添加「檢查以前」列?
- 16. ALTER TABLE sqlite:如何檢查列是否存在之前改變表?
- 17. 如何在連接之前檢查實體是否存在?
- 18. 如何在安裝之前檢查conda包是否存在?
- 19. 如何在調用之前檢查目標是否存在?
- 20. 如何在設置之前檢查圖像是否存在?
- 21. 如何在FtpWebRequest之前檢查FTP上是否存在文件
- 22. 如何檢查是否存在之前,在Dapper讀ORM
- 23. 如何檢查在PL/SQL中運行查詢之前列是否存在並且錶行數是否收集?
- 24. ActiveAndroid添加列與檢查是否存在或不
- 25. 在檢查值之前檢查變量是否存在
- 26. LINQ檢查是否存在在列表
- 27. 在將其添加到Android日曆之前檢查事件是否存在
- 28. 在將數據添加到datagridview之前檢查行是否存在
- 29. 在繼續添加元素之前檢查元素是否存在
- 30. 如何檢查數據列中是否存在列
我知道這是一年前,但如何從sqlite.swift得到userVersion?我試圖添加列可能或可能不存在的表,但我不太清楚如何做到這一點..如何檢查表是否存在?因爲使用'table.create(ifNotExists:true)'我不能做一個else存在,檢查列是否存在。另外我該如何檢查列是否存在? – apikurious