我有一个 SQLite 数据库,我想用一些初始数据填充它。
使用SQLite.swift ,这个方法似乎有效:
do {
let _ = try db.run( userDictionary.create(ifNotExists: false) {t in
t.column(wordId, primaryKey: true)
t.column(word, unique: true)
t.column(frequency, defaultValue: 1)
t.column(following, defaultValue: "")
})
} catch _ {
print("table already exists")
return
}
// Add some initial data for a new database
print("adding new data")
myMethodToInsertInitialData()
其工作方式是,我每次在初始数据库创建后都使用 ifNotExists: false
抛出错误。 (将其设置为 true 不会引发错误(或允许提前返回)。)但是,除了第一次之外,每次都故意引发错误似乎是糟糕的编程。我并不是真的认为这是一个错误。我只想在新创建的数据库中插入一些数据。有更好的方法来做到这一点还是每个人都这样做?
最佳答案
检查 SQLite.swift 中表中是否有数据
do
{
db = try Connection(YOUR_DB_PATH)
let intCount : Int64 = db.scalar("SELECT count(*) FROM yourTableName") as! Int64
if (intCount == 0)
{
//callWebServiceCall()
}
else
{
//getDataFromDB()
}
}
catch
{
print("error")
}
关于ios - 在 SQLite.swift 中创建数据库后插入初始数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37185087/