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?

4
  • You could set a Boolean in NSUserDefaults or a Property list plist to check if it is the first time running the app. Commented May 12, 2016 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. Commented May 12, 2016 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? ` Commented May 12, 2016 at 11:36
  • This creates a SQLite.swift table, not the actual database table, so there is no crash. Commented May 12, 2016 at 23:27

1 Answer 1

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")
}
Sign up to request clarification or add additional context in comments.

2 Comments

When I read the documentation I didn't understand scalars very well. So even if the table grows to be very large, this will be a fast lookup, correct?
@Suragch Yes It will just count!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.