我创建了一个使用sqlite.swift将json数据映射到sqlite存储的函数。我收到了奇怪的行为,但是自从我第一次尝试运行插入操作后,我得到了“没有这样的表”错误“。但是在初始抛出之后插件工作正常。我的代码通过使用SQLData连接到数据库onload来工作.instance.connect()。然后每次调用insert时,它都会初始化表,以确保它与数据中的所有列一起设置。
//附加到按钮
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
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)
}
}
}
}