I use the following simple wrapper:
private let _SingletonSharedInstance = SQLite()
class SQLite {
private var db: COpaquePointer = nil
private let path = "<path to your db>.rdb"
private var statement: COpaquePointer = nil
private let SQLITE_STATIC = sqlite3_destructor_type(COpaquePointer(bitPattern: 0)) // http://stackoverflow.com/a/26884081/1271826
private let SQLITE_TRANSIENT = sqlite3_destructor_type(COpaquePointer(bitPattern: -1))
class var sharedInstance : SQLite {
return _SingletonSharedInstance
}
init() {
if sqlite3_open(path, &db) != SQLITE_OK {
fatalError("database not found")
}
}
func select(query:String) -> Bool {
if sqlite3_prepare_v2(db, "SELECT (query)", -1, &statement, nil) == SQLITE_OK { return true }
let errmsg = String.fromCString(sqlite3_errmsg(db))
println("error preparing select: (errmsg!)")
return false
}
func prepare(query:String) -> Bool {
if sqlite3_prepare_v2(db, query, -1, &statement, nil) == SQLITE_OK { return true }// "insert into test (name) values (?)"
let errmsg = String.fromCString(sqlite3_errmsg(db))
println("error preparing '(query)': (errmsg!)")
return false
}
func bind(parm:Int, value:String) -> Bool {
if sqlite3_bind_text(statement, Int32(parm), value, -1, SQLITE_TRANSIENT) == SQLITE_OK { return true }
let errmsg = String.fromCString(sqlite3_errmsg(db))
println("failure binding foo: (errmsg!)")
return false
}
func execute() -> Bool {
if sqlite3_step(statement) == SQLITE_DONE { return true }
let errmsg = String.fromCString(sqlite3_errmsg(db))
println("failure in execute: (errmsg!)")
return false
}
func lastId() -> Int {
return Int(sqlite3_last_insert_rowid(db))
}
func nextRow() -> Bool {
if sqlite3_step(statement) == SQLITE_ROW { return true }
statement = nil
return false
}
func intAt(col:Int) -> Int {
return Int(sqlite3_column_int64(statement, Int32(col)))
}
func textAt(col:Int) -> String {
let name = sqlite3_column_text(statement, Int32(col))
if name != nil {
return String.fromCString(UnsafePointer<Int8>(name))!
}
return ""
}
}
and then in the single classes:
let sqLite = SQLite.sharedInstance
sqLite.select("* FROM table")
while sqLite.nextRow() {
println(sqLite.textAt(0))
}
I guess the rest is obvious.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…