Using SQLite from Swift

It’s been a while since I experimented with using SQLite from Swift (like a few years). I found it painful the last time I tried, but thought I’d revisit it again. To my delight, it turns out to be straightforward.

I found useful information on Stack Overflow, but the essentials are that you can simply do the following


import SQLite3

let dbPath = "database.db"

var db: OpaquePointer?
guard sqlite3_open(dbPath, &db) == SQLITE_OK else {
    sqlite3_close(db)
    db = nil
    print("Error opening database \(dbPath)")
    return
}

When I first tried this from a Mac OS/X app I was building, the sqlite3_open() call failed and I couldn’t figure out why. Eventually I realised that with the new security model in OS/X, the app had to first obtain permission to access the database.

The easiest way to do this was to create a file open dialog using NSOpenPanel(), so that the user can choose the database file themselves. After that, all the sqlite3 functions worked as expected.