完成本教程后
http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_8_Application_using_Swift_and_FMDB
我发现数据库仅在应用程序运行时创建。我第二次运行应用程序时如何访问数据库。我的最终目标是创建一个数据库并使用数据来显示事物。
答案 0 :(得分:2)
我使用以下简单的包装器:
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 ""
}
}
然后在单个班级中:
let sqLite = SQLite.sharedInstance
sqLite.select("* FROM table")
while sqLite.nextRow() {
println(sqLite.textAt(0))
}
我猜其余的很明显。