在 SQLite.swift 中创建数据库后插入初始数据

Inserting initial data after database creation in SQLite.swift

我有一个 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 不会抛出错误(或允许早期的 return)。)但是,除了第一次之外每次都故意抛出错误似乎是糟糕的编程。我并不是真的认为这是一个错误。我只想在新创建的数据库中插入一些数据。有没有更好的方法来做到这一点,还是每个人都这样做?

检查 table 中是否有数据 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")
}