0

Hi I'm working in a Swift project and using sqlite database in it. In Objective-C, we just import sqlite3.h in class file and create a instance for sqlite3 like
sqlite3 *db;
and we use it through out the program.

Like wise how do I achieve it in swift ??

  • possible duplicate of [Accessing an SQLite Database in Swift](http://stackoverflow.com/questions/24102775/accessing-an-sqlite-database-in-swift) – Eric Aya May 29 '15 at 07:55
  • In that link they haven't mentioned how to create a instance for sqlite3. – Dayanithi Natarajan May 29 '15 at 08:00
  • Yes they have, chapter 2 of this answer: http://stackoverflow.com/a/28642293/2227743. You could use the excellent https://github.com/stephencelis/SQLite.swift instead, anyway. – Eric Aya May 29 '15 at 08:07
  • Follow this step by step : http://www.theappguruz.com/tutorial/use-sqlite-database-swift/ – Dharmesh Kheni May 29 '15 at 08:07

1 Answers1

0

From https://github.com/ryanfowler/SwiftData/blob/master/SwiftData.swift

private class SQLiteDB {

    class var sharedInstance: SQLiteDB {
        struct Singleton {
            static let instance = SQLiteDB()
        }
        return Singleton.instance
    }

    var sqliteDB: COpaquePointer = nil
    var dbPath = SQLiteDB.createPath()
    var inTransaction = false
    var isConnected = false
    var openWithFlags = false
    var savepointsOpen = 0
    let queue = dispatch_queue_create("SwiftData.DatabaseQueue", DISPATCH_QUEUE_SERIAL)


    // MARK: - Database Handling Functions

    //open a connection to the sqlite3 database
    func open() -> Int? {

        if inTransaction || openWithFlags || savepointsOpen > 0 {
            return nil
        }
        if sqliteDB != nil || isConnected {
            return nil
        }
        let status = sqlite3_open(dbPath.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB)
        if status != SQLITE_OK {
            println("SwiftData Error -> During: Opening Database")
            println("                -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
            if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
                println("                -> Details: \(errMsg)")
            }
            return Int(status)
        }
        isConnected = true
        return nil

    }
}

Don't forget to link your target against libsqlite3.dylib

ezcoding
  • 2,974
  • 3
  • 23
  • 32