How to Create and Open a SQLite Database in Swift

In this article, we will explain how to create and open a SQLite database in Swift.

We will continue by adding code to the app created in Create a Test iOS App for SQLite.


To create a SQLite database (if it does not already exist) and open it, we use the sqlite3_open() function.

Open the DBService.swift file and add the following code:

import Foundation
import SQLite3

final class DBService {
    static let shared = DBService()
    
    private let dbFile = "DBVer1.sqlite"
    private var db: OpaquePointer?
    
    private init() {
        db = openDatabase()
    }
    
    private func openDatabase() -> OpaquePointer? {
        let fileURL = try! FileManager.default.url(for: .documentDirectory,
                                                   in: .userDomainMask,
                                                   appropriateFor: nil,
                                                   create: false).appendingPathComponent(dbFile)
        
        var db: OpaquePointer? = nil
        if sqlite3_open(fileURL.path, &db) != SQLITE_OK {
            print("Failed to open database")
            return nil
        }
        else {
            print("Opened connection to database")
            return db
        }
    }
}

Let’s go through the code step by step:

Line 7 defines the database file name for SQLite and assigns it to dbFile.

In this example, the file name is DBVer1.sqlite.


Line 8 declares a variable db of type OpaquePointer?, which will be used to interact with the SQLite database.

Lines 10–12 contain the initializer. When an instance of the DBService class is created, the openDatabase() function is executed and its return value is assigned to db.


Lines 14–29 define the openDatabase() function, which creates a new SQLite database if one does not exist and returns an OpaquePointer.

Lines 15–18 use FileManager.default.url() to get the URL of the user’s documentDirectory and append the SQLite database file name to create fileURL.


Line 20 declares a local variable db of type OpaquePointer?.

Line 21 calls sqlite3_open(), passing in fileURL.path and db as arguments to open the SQLite database.

If the specified path does not contain a database file, a new one is created and then opened.


If the database opens successfully, the pointer is set to db and sqlite3_open() returns SQLITE_OK.

Lines 22–23 handle the failure case, printing an error message and returning nil.

Lines 26–27 handle the success case, printing a success message and returning db.


This is how you create and open a SQLite database in Swift.

Next, we will create a table in the SQLite database.

Next article: "Create a Table in SQLite with Swift"