gpt4 book ai didi

sqlite - Sqlite.swift没有这样的表错误

转载 作者:行者123 更新时间:2023-12-03 18:08:34 28 4
gpt4 key购买 nike

我创建了一个函数,用于使用sqlite.swift将json数据映射到sqlite存储。尽管自从我第一次尝试运行插入操作时,我收到一个奇怪的行为,但是却收到“没有这样的表”错误。 .instance.connect()。然后,每次放置插入调用时,它将初始化该表,以确保该表已使用数据中的所有列进行设置。

//附加到按钮

let userJSON = JSON(["user_id" : id, "username" : email])

SQLData.instance.insert(table: "users", data: userJSON) { result in
if let result = result{
print(result)
}
}


// sql类

class SQLData {
static let instance = SQLData()
var db: Connection? = nil

func connect() {
let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first!
do {
self.db = try Connection("\(path)/contacts.sqlite3")
if let db = self.db {
try db.run(Table("users").drop(ifExists: true))
}
print("SQLite connection established.")
} catch {
print("Couldn't create SQLite connection.")
}
}

func initTable(table: String, data: JSON, completionHandler: (Table?) -> Void){
if let db = db {
let t = Table(table)

do {
try db.run(t.create(temporary: false, ifNotExists: true) { r in
r.column(Expression<Int>("id"), primaryKey: true)
r.column(Expression<Bool>("synced"), defaultValue: false)

for (key,val) in data {
if val.bool != nil{
r.column(Expression<Bool>(key), defaultValue: false)
} else if val.int != nil {
r.column(Expression<Int>(key), defaultValue: 0)
} else if val.double != nil {
r.column(Expression<Double>(key), defaultValue: 0.0)
} else {
r.column(Expression<String?>(key), defaultValue: "")
}
}
completionHandler(t)
})
} catch let err {
print(err)
completionHandler(nil)
}
} else {
completionHandler(nil)
}
}

func insert(table: String, data: JSON, completionHandler: @escaping (Int64?) -> Void){
self.initTable(table: table, data: data) { t in
if let db = db, let t = t {
var query: [Setter] = []
for (key, val) in data {
if val.bool != nil{
query.append(Expression<Bool>(key) <- val.boolValue)
} else if val.int != nil {
query.append(Expression<Int>(key) <- val.intValue)
} else if val.double != nil {
query.append(Expression<Double>(key) <- val.doubleValue)
} else {
query.append(Expression<String?>(key) <- val.stringValue)
}
}
do {
try db.transaction {
let insert = t.insert(query)
let rowid = try db.run(insert)
completionHandler(rowid)
}
} catch let err {
print(err)
completionHandler(nil)
}
} else {
completionHandler(nil)
}
}
}
}

最佳答案

如下更改连接功能

func connect(){
do {
let databaseFilePath = Bundle.main.path(forResource: "contacts", ofType: "sqlite3")!
db = try Connection(databaseFilePath)
} catch {
print(error)
}
}


并确保将.sqlite3(或.db)文件放入项目层次结构中,并复制捆绑包资源(例如图像)

enter image description here

enter image description here

关于sqlite - Sqlite.swift没有这样的表错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41510104/

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