import SQLite3
// 创建或打开数据库
guard let db = openDatabase(atPath: "path/to/database.sqlite") else {
fatalError("无法打开数据库")
}
// 创建表格
guard createTable(inDatabase: db) else {
fatalError("无法创建表格")
}
// 插入数据
guard insertData(intoDatabase: db) else {
fatalError("无法插入数据")
}
// 查询数据
guard let results = queryData(fromDatabase: db) else {
fatalError("无法查询数据")
}
print(results)
// 关闭数据库
closeDatabase(db)
// 打开SQLite数据库
func openDatabase(atPath path: String) -> OpaquePointer? {
var db: OpaquePointer?
if sqlite3_open(path, &db) != SQLITE_OK {
print("无法打开数据库: \(String(cString: sqlite3_errmsg(db)))")
return nil
}
return db
}
// 创建表格
func createTable(inDatabase db: OpaquePointer) -> Bool {
let createTableSQL = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT);"
var statement: OpaquePointer?
if sqlite3_prepare_v2(db, createTableSQL, -1, &statement, nil) == SQLITE_OK {
if sqlite3_step(statement) != SQLITE_DONE {
print("创建表格失败: \(String(cString: sqlite3_errmsg(db)))")
return false
}
} else {
print("语法错误: \(String(cString: sqlite3_errmsg(db)))")
return false
}
sqlite3_finalize(statement)
return true
}
// 插入数据
func insertData(intoDatabase db: OpaquePointer) -> Bool {
let insertSQL = "INSERT INTO users (name, email) VALUES (?, ?);"
var statement: OpaquePointer?
if sqlite3_prepare_v2(db, insertSQL, -1, &statement, nil) == SQLITE_OK {
sqlite3_bind_text(statement, 1, "John Doe", -1, nil)
sqlite3_bind_text(statement, 2, "johndoe@example.com", -1, nil)
if sqlite3_step(statement) != SQLITE_DONE {
print("插入数据失败: \(String(cString: sqlite3_errmsg(db)))")
return false
}
} else {
print("语法错误: \(String(cString: sqlite3_errmsg(db)))")
return false
}
sqlite3_finalize(statement)
return true
}
// 查询数据
func queryData(fromDatabase db: OpaquePointer) -> [[String: String]]? {
let querySQL = "SELECT id, name, email FROM users;"
var statement: OpaquePointer?
var results: [[String: String]] = []
if sqlite3_prepare_v2(
评论已关闭