use of SQLite with swift in iOS 9,2

fabiodelorenzo
Posts: 65
Joined: Thu Oct 03, 2013 5:54 pm

use of SQLite with swift in iOS 9,2

Postby fabiodelorenzo » Fri Jan 01, 2016 7:55 pm

SQLite is implemented in Objective-C.
If you want to use it with Swift, you must wrap the C libraries with some Swift code.
Either by yourself or use one of the (few) libraries available.
I used: SQLite.swift-master (https://github.com/stephencelis/SQLite.swift)
and installed manually:
    Download the wrapper from https://github.com/stephencelis/SQLite. ... master.zip
    Using Finder (do not copy using the console) drag the SQLite.xcodeproj file into your own project
    In your target’s General tab, click the + button under Linked Frameworks and Libraries
    Select the appropriate SQLite.framework for your platform (eg, SQLite iOS if you do iOS development)

Code: Select all

import SQLite

let users = Table("users")
let id = Expression<Int64>("id")
let email = Expression<String>("email")
let name = Expression<String?>("name")
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true ).first!


Then, to create a DB myDataBase.sqlite3:

Code: Select all

        let db = try! Connection("\(path)/myDataBase.sqlite3")
        db.trace { print($0) }


Let's say I have a table with 3 columns: id, email and name:

Code: Select all

        try! db.run(users.create { t in
            t.column(id, primaryKey: true)
            t.column(email, unique: true, check: email.like("%@%"))
            t.column(name)
            })



Insert a record:

Code: Select all

        let db = try! Connection("\(path)/myDataBase.sqlite3")
        let mEmail = "fabio@crokky.com"
        let mName = "Fabio"
        let rowid = try! db.run(users.insert(email <- mEmail, name <- mName) )


Extract data:

Code: Select all

        for user in db.prepare(users) {
            print("id: \(user[id]), email: \(user[email])")

Return to “Swift basic”

Who is online

Users browsing this forum: No registered users and 1 guest