class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
update()
}
// 修改数据
func update() -> Void {
// sql (需改id为2的一条数据)
let sql = "UPDATE T_Person SET name = ?, age = ?, height = ? WHERE id = 2"
// 执行sql
SQLManager.sharedTools.queue.inDatabase { (db) in
let result = db.executeUpdate(sql, withArgumentsInArray: ["老李",20,189.3])
if result {
print("修改成功")
} else {
print("修改失败")
}
}
}
}
SQLManager.swift:
// 数据库名称
private let dbName = "dataSources.db"
class SQLManager {
// 全局访问点
static let sharedTools: SQLManager = SQLManager()
// 队列方式
let queue: FMDatabaseQueue
// 构造函数
private init(){
// 打开数据库
// 获取路径
let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent(dbName)
// 队列方式
queue = FMDatabaseQueue(path: path)
// 创建表
createTable()
// 打印路径
print(path)
}
// MARK: - 创建表
private func createTable() -> Void {
// 获取文件
let file = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)!
// 准备sql
let sql = try! String(contentsOfFile: file)
// 执行sql
queue.inDatabase { (db) in
let result = db.executeStatements(sql)
if result {
print("创建表成功")
} else {
print("创建表失败")
}
}
}
}
创建表的SQL语句放在单独的文件db.sql中:
-- 创建个人表 --
CREATE TABLE IF NOT EXISTS "T_Person" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" TEXT,
"age" INTEGER,
"height" REAL
);
-- 创建图书表 --
CREATE TABLE IF NOT EXISTS "T_Book" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"bookName" TEXT
);