Importing and querying through an SQLite database in Swift - iOS Importing and querying through an SQLite database in Swift - iOS sqlite sqlite

Importing and querying through an SQLite database in Swift - iOS


The process is as follows:

  1. Add the database to your bundle. When you drag it into your project, you can choose to add it to the target that represents your main app. Alternatively, review the target settings, click on "Build Phases" and confirm the database appears in the "Copy Bundle Resources" list.

  2. Use a framework like FMDB to simplify your life. This is written in Objective-C, but works great in Swift, too. What you need to do is:

    • Copy the .h and .m files for FMDB into your project;

    • When prompted to create a "bridging header", do so;

    • Add the following line to your bridging header:

      #import "FMDB.h"

    By following those steps, you can use this framework developed in Objective-C into your Swift projects.

  3. You can now write your Swift code, using the FMDB framework. For example, the Swift code to open the database, select columns x, y, and z from a table called test, would look like:

    let path = NSBundle.mainBundle().pathForResource("test", ofType:"sqlite")let database = FMDatabase(path: path)if !database.open() {    print("Unable to open database")    return}if let rs = database.executeQuery("select * from test", withArgumentsInArray: nil) {    while rs.next() {        let x = rs.stringForColumn("x")        let y = rs.stringForColumn("y")        let z = rs.stringForColumn("z")        print("x = \(x); y = \(y); z = \(z)")    }} else {    print("executeQuery failed: \(database.lastErrorMessage())")}database.close()


Swift only. No Objective-C files required.

Here is another solution which uses SQLite.swift instead of FMDB.

1.: Get a valid path to your database file

Don't save the database file in your Assets folder, but add it to your Copy Bundle Resources list in the Build Phases setting of your current target. If your file is called myDb.db you can then get a valid path like this:

let dbUrl = Bundle.main.url(forResource: "myDb", withExtension: "db")!let dbPath = dbUrl.path

2.: Access your database (without copying it)

It is possible to access your database now without having to (manually?) copy it. Just use the SQLite.swift library:

db = try! Connection(dbPath)

Notes:The only thing I haven't checked yet explicitly is writing to the database. At least a read-only access does work like a charm though.