外国大神写的 SQLite.swift
大家可以去看下 github 的使用说明,无需SQL语句即可方便使用..
下面简单在大神的SQLite.Swift库上封装下,方便简单使用
只是使用 三个列表数 id name email ,大家可以根据需求对这个结构体进行自定义...
import UIKit
import SQLite
struct SQLiteManager {
private var db: Connection!
private let users = Table("users") //表名
private let id = Expression<Int64>("id") //主键
private let name = Expression<String>("name") //列表1
private let email = Expression<String>("email") //列表2
init() {
createdsqlite3()
}
//创建数据库文件
mutating func createdsqlite3(filePath: String = "/Documents") {
let sqlFilePath = NSHomeDirectory() + filePath + "/db.sqlite3"
do {
db = try Connection(sqlFilePath)
try db.run(users.create { t in
t.column(id, primaryKey: true)
t.column(name)
t.column(email, unique: true)
})
} catch { print(error) }
}
//插入数据
func insertData(_name: String, _email: String){
do {
let insert = users.insert(name <- _name, email <- _email)
try db.run(insert)
} catch {
print(error)
}
}
//读取数据
func readData() -> [(id: String, name: String, email: String)] {
var userData = (id: "", name: "", email: "")
var userDataArr = [userData]
for user in try! db.prepare(users) {
userData.id = String(user[id])
userData.name = user[name]
userData.email = user[email]
userDataArr.append(userData)
}
return userDataArr
}
//更新数据
func updateData(userId: Int64, old_name: String, new_name: String) {
let currUser = users.filter(id == userId)
do {
try db.run(currUser.update(name <- name.replace(old_name, with: new_name)))
} catch {
print(error)
}
}
//删除数据
func delData(userId: Int64) {
let currUser = users.filter(id == userId)
do {
try db.run(currUser.delete())
} catch {
print(error)
}
}
}
使用:
let sqliteContext = SQLiteManager() //如果没有,默认创建数据库及表格
//插入数据
sqliteContext.insertData("username", _email: "email@126.com")
//读取全部数据
//要想读取指定数据,可以自己自定义转换成其他模型,比如字典+元组,可以根据id查找
let dataM = sqliteContext.readData()
print(dataM)
//更新数据 1 -> 用户id
sqliteContext.updateData(1, old_name: "oldValue", new_name: "newValue")
//删除数据
sqliteContext.delData(1) // 1 -> 用户id
网友评论