ios swift sqlite3 简单使用
import Foundation
// 定义数据库操作类
class SQLiteDB {
var db: OpaquePointer? = nil
// 初始化数据库
init?(dbPath: String) {
if sqlite3_open(dbPath.cString(using: .utf8), &db) != SQLITE_OK {
sqlite3_close(db)
return nil
}
}
// 关闭数据库
deinit {
sqlite3_close(db)
}
// 执行非查询SQL语句
func exec(sql: String) -> Bool {
var statement: OpaquePointer? = nil
if sqlite3_prepare_v2(db, sql.cString(using: .utf8), -1, &statement, nil) != SQLITE_OK {
sqlite3_finalize(statement)
return false
}
if sqlite3_step(statement) != SQLITE_DONE {
sqlite3_finalize(statement)
return false
}
sqlite3_finalize(statement)
return true
}
// 查询SQL语句
func query(sql: String) -> [[String: String]] {
var statement: OpaquePointer? = nil
var results: [[String: String]] = []
if sqlite3_prepare_v2(db, sql.cString(using: .utf8), -1, &statement, nil) != SQLITE_OK {
sqlite3_finalize(statement)
return results
}
while sqlite3_step(statement) == SQLITE_ROW {
var rowData: [String: String] = [:]
let columnCount = sqlite3_column_count(statement)
for i in 0..<columnCount {
let columnName = String(cString: sqlite3_column_name(statement, i))
let value = sqlite3_column_text(statement, i)
if let text = value {
rowData[columnName] = String(cString: text)
}
}
results.append(rowData)
}
sqlite3_finalize(statement)
return results
}
}
// 使用示例
let dbPath = "path/to/database.sqlite3"
let db = SQLiteDB(dbPath: dbPath)
// 创建表
let createTableSQL = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)"
db?.exec(sql: createTableSQL)
// 插入数据
let insertSQL = "INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')"
db?.exec(sql: insertSQL)
// 查询数据
let selectSQL = "SELECT * FROM users"
let results = db?.query(sql: selectSQL)
// 输出查询结果
if let rows = results {
for row in rows {
print(row)
}
}
这个代码示例展示了如
评论已关闭