65.9K
CodeProject is changing. Read more.
Home

SQLite Wrapper for iOS in Swift

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (3 votes)

May 29, 2016

CPOL

1 min read

viewsIcon

19441

downloadIcon

198

An easy SQLite Wrapper for iOS in swift that allows you to create a database and run SQL commands

Introduction

This is an easy One-Class Wrapper for most of your SQL needs while working with iOS.

Background

I am working on an app that will be searching and manipulating a large amount of data, so I decided to seed and store the data in a database instead of holding it in memory and praying the app will not crash. I was unable to find anything easy to use, and even the tutorials did not give instructions on actually making anything work. They just gave a few commands, so I decided to write my own wrapper.

Using the Code

To add SQLite functions to your project:

  1. Make sure that the libsqlite3.tbd is linked to the project and you can do that in the General Settings of the app
  2. Add a header file to the project and call it BridgingHeader.h and type the following line to include the C API:
    #include <sqlite3.h>
  3. Go to "Build Settings" and find "Objective-C Bridging Header." Use the search bar to find it quickly. Double-click and type "BridgingHeader.h". If you get "Could not import Objective-C Header," try "my-project-name/BridgingHeader.h"
  4. Go to "Build Phases," "Link Binary With Libraries," and add libsqlite3.tbd
  5. Add in the SQLDataIO.swift to your project (or just create a new one and copy/paste the code in from this sample project)

Functions:

  • updateDatabase
  • dbValue
  • dbInt
  • nextID
  • getRows

To use:

        var dbCommand: String = ""
        dbCommand = "CREATE TABLE Family(ID INT PRIMARY KEY NOT NULL, 
        FirstName CHAR(100), LastName CHAR(100), Age INT);"
        updateDatabase(dbCommand)
        
        var databaseRows: [[String]] = [[]]
        var id: Int = 0

        for i in 0...6
        {
            id = nextID("Family")

            dbCommand = "insert into Family(ID, FirstName, LastName, Age) 
            values (\(id), '\(firstName[i])', '\(lastName[i])', '\(age[i])')"

            updateDatabase(dbCommand)
        }        

        dbCommand = "select ID, FirstName, LastName, Age from Family"
        databaseRows = getRows(dbCommand, numColumns: 4)
       
        dbCommand = "UPDATE Family SET FirstName = 'Adam' WHERE ID = 1;"
        updateDatabase(dbCommand)
        
        dbCommand = "select LastName from Family where ID = 1"
        let lName: String! = dbValue(dbCommand)

        dbCommand = "select Age from Family where ID = 2"
        let ageInt: Int = dbInt(dbCommand)

        dbCommand = "select Age from Family where ID = 2"
        let ageString: String  = dbValue(dbCommand)
        
        dbCommand = "DELETE FROM Family WHERE ID = 1;"
        updateDatabase(dbCommand)

History

  • 29th May, 2016: Initial version