1

I plan on updating an old application which is currently using a SQLITE database.

My new application is written in iOS8/Swift.

Is there an easy way to run a select statement on SQLite database file and iterate through the results? While doing this I'll be transferring the information into a new Core Data database.

eg: select id, someDate, someString, someInt from myTable;

After I've performed this select statement I will never do anything else with SQLite so i'm not looking at adding anything major to the application. Just a very quick select to grab seeding data.

Hope this makes sense. I'm just confused when trying to do this in Swift.

====== UPDATE ======

I'm going with SQLite.swift. Easy to setup and get running.

The following is working but am I correctly checking if the values are NOT NIL? Is this the best way to check?

let stmt = db.prepare("SELECT anID, aString FROM someTable")
for row in stmt {

    if var myID:Int = row[0] as Int? {  // do something here if exists  }
    if var myString:String = row[1] as String? {  // do something here if exists  }

}
2
  • You can simplify a bit by only declaring the type once, and I believe you meant to use let to unwrap, e.g., if let myID = row[0] as Int? { /* ... */ }. (Also, the second should be row[1].) Commented Oct 31, 2014 at 6:49
  • Thank you, makes sense. The [2] was a copy paste mistake. Updated. Commented Oct 31, 2014 at 7:12

2 Answers 2

5

There is always FMDB, but it's definitely living in the Objective-C ages. I wrote SQLite.swift to work better with the Swift programming language.

Your example above would most simply look like this:

let stmt = db.prepare("SELECT id, someDate, someString, someInt FROM myTable")
for row in stmt {
    // [Optional(1), Optional("2014-10-30"), Optional("Hello!"), Optional(5)]
}
Sign up to request clarification or add additional context in comments.

2 Comments

Works great. Thank you. I've updated my original question for further clarification on the best way to check if values are Nil.
Replied. By default there's no way to guarantee at compile time that a column value will never be NULL, so optionals are the way to go, and your decision to use iflet is the standard.
0

FMDB is an amazing third party library that interfaces with sqlite.

A detailed swift FMDB tutorial can be found here

Comments

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.