您好我正在使用Swift项目并在其中使用sqlite数据库。在Objective-C中,我们只需在类文件中导入sqlite3.h
并为sqlite3
创建一个像实例一样的实例
sqlite3 *db;
我们在整个计划中使用它。
同样明智的我如何在swift中实现它?
答案 0 :(得分:0)
来自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
}
}
不要忘记将目标链接到 libsqlite3.dylib