class SQLite3Manager: NSObject
{
let DBFILE_NAME = "sqlitedemo.db"
private var db: OpaquePointer? = nil
func create_database()
{
// 数据库路径
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let sqlitePath = "\(urls[urls.count-1].absoluteString)\(DBFILE_NAME)"
if sqlite3_open(sqlitePath, &db) == SQLITE_OK{
let sql = "CREATE TABLE IF NOT EXISTS
tb_test(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)"
if sqlite3_exec(db, sql, nil, nil, nil) != SQLITE_OK {
print("create table error")
}
sqlite3_close(db)
}
else{
print("open sqlite3 error.")
}
}
}
if sqlite3_open(sqlitePath, &db) == SQLITE_OK{
let sql = "SELECT id, name, age FROM tb_test WHERE name=?"
let cSql = sql.cString(using: .utf8)
var statement :OpaquePointer? = nil
// 预处理SQL语句
if sqlite3_prepare_v2(db, cSql, -1, &statement, nil) == SQLITE_OK {
let name = "Jobs"
let cName = name.cString(using: .utf8)
// 绑定参数
sqlite3_bind_text(statement, 1, cName!, -1, nil)
// 遍历结果集
if sqlite3_step(statement) == SQLITE_ROW {
// 提取字段数据
let id = sqlite3_column_int(statement, 0)
let name = String(cString: UnsafePointer(sqlite3_column_text(statement, 1)))
let age = sqlite3_column_int(statement, 0)
print("id:\(id);name:\(name);age:\(age)")
}
}
sqlite3_finalize(statement)
sqlite3_close(db)
}