gpt4 book ai didi

swift - 如何在 SQLite.swift 中升级数据库版本并在 swift 表中添加新列

转载 作者:搜寻专家 更新时间:2023-10-31 22:39:16 24 4
gpt4 key购买 nike

如何在 SQLite.swift 中升级数据库版本并在 swift 中的表中添加新列 am 使用 https://github.com/stephencelis/SQLite.swift/blob/master/Documentation/Index.md

//migration of db version


extension Connection {
public var userVersion: Int32 {
get { return Int32(try! scalar("PRAGMA user_version") as! Int64)}
set { try! run("PRAGMA user_version = \(newValue)") }
}
}
//in viewdidLoad of viewcontroller
if db.userVersion == 0 {
// handle first migration
db.userVersion = 1
}
if db.userVersion == 1 {
// handle second migration
db.userVersion = 2
}
//my table and want to upgrade with some new columns
do
{
let offlineLocationTable = sqliteOfflineLocationTable.offlineLocationTable.create(ifNotExists: true) { (table) in
table.column(sqliteOfflineLocationTable.id, primaryKey: true)
table.column(sqliteOfflineLocationTable.status)
table.column(sqliteOfflineLocationTable.loadid)
table.column(sqliteOfflineLocationTable.jobid)
table.column(sqliteOfflineLocationTable.lat)
table.column(sqliteOfflineLocationTable.lng)
// this is new columns which i want to add in new version of db
table.column(sqliteOfflineLocationTable.t)
print("offline location table created")
}
try self.db.run(offlineLocationTable)
} catch {
print(error)
}

// this code run successfully but when i try to get the column value it carsh due to No such column "t" in columns [........]

最佳答案

我没试过,你可以试试这个。在 Swift 中,您可以为连接类创建一个新的扩展文件。

extension Connection {
public var userVersion: Int32 {
get { return Int32(try! scalar("PRAGMA user_version") as! Int64)}
set { try! run("PRAGMA user_version = \(newValue)") }
}
}

注意:请检查下面代码的语法,因为我无法判断你的变量

如果表不存在,您的表将根据您的代码创建。

//in viewdidLoad of viewcontroller
if db.userVersion == 0 {
// handle first migration
do
{
let offlineLocationTable = sqliteOfflineLocationTable.offlineLocationTable.create(ifNotExists: true) { (table) in
table.column(sqliteOfflineLocationTable.id, primaryKey: true)
table.column(sqliteOfflineLocationTable.status)
table.column(sqliteOfflineLocationTable.loadid)
table.column(sqliteOfflineLocationTable.jobid)
table.column(sqliteOfflineLocationTable.lat)
table.column(sqliteOfflineLocationTable.lng)
// any other table entries
}
try self.db.run(offlineLocationTable)
// on complete of first table creation change the version
db.userVersion = 1
} catch {
print(error)
}
}
if db.userVersion == 1 {
// handle second migration
// Here we add New Column in table
do
{
try self.db.run(offlineLocationTable.addColumn(t, defaultValue: ""))
// any other modifications
db.userVersion = 2
} catch {
print(error)
}
}

现在编写您的任何其他代码。

关于swift - 如何在 SQLite.swift 中升级数据库版本并在 swift 表中添加新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51302988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com