0

I have a SQLite database that I want to populate with some initial data.

Using SQLite.swift, this method seems to be working:

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. (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. 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?

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • You could set a Boolean in `NSUserDefaults` or a Property list `plist` to check if it is the first time running the app. – TPlet May 12 '16 at 11:20
  • @TPlet, I considered that and it is a valid option. The reason I am leaning away from it, though, is that I could conceivably delete the database table and recreate it some time after the first run. With the above method, I add the initial data when (and only when) the database table gets created. – Suragch May 12 '16 at 11:26
  • Oh well ok. I didn't use SQLite.swift so I have a question here: In the docs it says that you can access a Table with e.g. `let users = Table('users')` . What happens if this table does not exist? Is it just nil, or does it crash? ` – TPlet May 12 '16 at 11:36
  • This creates a SQLite.swift table, not the actual database table, so there is no crash. – Suragch May 12 '16 at 23:27

1 Answers1

1

To check whether data is available in table or not in 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")
}
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136