Search code examples
iossqliteselectswift

iOS Simple SQLite Select Statement in Swift


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  }

}

Solution

  • 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)]
    }