导入SQLite.swift
推荐使用CocoaPods进行导入,CocoaPods是一个负责管理iOS项目中第三方开源库的工具,安装CocoaPods之后使用命令行就能轻松地对所有第三方开源库进行安装和更新,而不需要每次上GitHub去下载。
导入完成后
在你需要用到SQLite.swift的类中加上:
import SQLite
链接数据库
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let db = try? Connection("\(path)/db.sqlite3")
创建表
fileprivate let person = Table("Person")
fileprivate let id = Expression<Int64>("id")
fileprivate let name = Expression<String>("name")
do {
try db.run(person.create{ t in
t.column(id, primaryKey: true)
t.column(name)
})
} catch {
print(error)
}
插入数据
let insert = person.insert(name <- "\(nameStr)")
do {
try db.run(insert)
} catch {
print(error)
}
查询数据
var arr = [String]()
// person.filter(name == "条件")
guard let persons = try?db.prepare(person) else {return arr}
for p in persons {
arr.append(p[name])
}
return arr
修改数据
//条件
let uP = person.filter(id == 4)
do {
try db.run(uP.update(name <- "\(newName)"))
} catch {
print(error)
}
删除数据
//删除数据
let uP = person.filter(id == pid)
do {
try db.run(uP.delete())
} catch {
print(error)
}
//删除表
do {
try db.run(person.drop())
} catch {
print(error)
}