Content of SQLite

by keen

SQLite is a relational database management system. In iOS, you can use it to store local data, query or update data. Actually I no longer use SQLite in my iOS App, I use Realm instead. But for some reasons, you may need to use SQLite. In this post, I’ll show you to use SQLite in your iOS Swift app.

My database file has a table called “person” with following records:

name                                                        country


Zhao Wei                                                  China

Lee Young-ae                                           South Korea

Will Smith                                                  US

Chen Kun                                                  China


After you create your SQLite file, open Xcode and create a new iOS project, language is Swift. Add you SQLite file to your project, make sure you check Copy items if needed.

In this project, we’ll use SQLiteDB library to work with SQLite

Download and extract it, then add following files to your project: Bridging-Header.h, SQLiteDB.swift, String-Extras.swift.

Go to Build Settings, double-click on Objective-C Bridging Header and set bridging header path to Bridging-Header.h. You can do that by dragging Bridging-Header.h to Objective-C Bridging Header panel.

Go to General -> Linked Frameworks and Libraries, add libsqlite3.0.dylib.

Build your project to make sure all things worked.


Working with SQLiteDB

In order to work with SQLiteDB, first, we need to obtain an SQLiteDB instance.

let db = SQLiteDB.sharedInstance()

To execute query commands, we use SQLiteDB.query method:

var result = db.query( "select * from person where country = 'China'" , parameters : nil)
for row in result
      println(row[ "name" ]!.asString())

To execute non-query commands, we use SQLiteDB.execute method:

db.execute( "delete from person where country = 'US'" , parameters : nil)

Here is my sample project. You might want to check it out.
I hope you like this post and see you next time.