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 SwiftEric Aya– Eric Aya2015-05-29 07:55:16 +00:00Commented May 29, 2015 at 7:55
-
In that link they haven't mentioned how to create a instance for sqlite3.Dayanithi Natarajan– Dayanithi Natarajan2015-05-29 08:00:27 +00:00Commented May 29, 2015 at 8:00
-
Yes they have, chapter 2 of this answer: stackoverflow.com/a/28642293/2227743. You could use the excellent github.com/stephencelis/SQLite.swift instead, anyway.Eric Aya– Eric Aya2015-05-29 08:07:03 +00:00Commented May 29, 2015 at 8:07
-
Follow this step by step : theappguruz.com/tutorial/use-sqlite-database-swiftDharmesh Kheni– Dharmesh Kheni2015-05-29 08:07:44 +00:00Commented May 29, 2015 at 8:07
Add a comment
|
1 Answer
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