简体   繁体   English

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

[英]Inserting initial data after database creation in SQLite.swift

I have a SQLite database that I want to populate with some initial data. 我有一个要填充一些初始数据的SQLite数据库。

Using SQLite.swift , this method seems to be working: 使用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()

The way this works, though is that I am using ifNotExists: false to throw an error every time after the initial database creation. 但是,这种方式的工作方式是我使用ifNotExists: false来在初始数据库创建后每次都抛出错误。 (Setting it to true would not throw an error (or allow the early return).) However, throwing an error on purpose every time except the first time seems like poor programming. (将其设置为true不会引发错误(或允许提早返回)。)但是,每次都有意抛出错误(第一次除外)似乎编程不好。 I don't really mean it as an error. 我不是真的把它当作错误。 I just want to insert some data in a newly created database. 我只想在新创建的数据库中插入一些数据。 Is there a better way to do this or is this what everyone does? 有没有更好的方法可以做到这一点,或者这是每个人都在做的事情吗?

To check whether data is available in table or not in SQLite.swift 检查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")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM