import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
delete()
}
// 刪除數(shù)據(jù)
func delete() -> Void {
// 準備sql
let sql = "DELETE FROM T_Person WHERE id = 3"
// 執(zhí)行sql
SQLManager.sharedTools.queue.inDatabase { (db) in
let result = db.executeUpdate(sql, withArgumentsInArray: nil)
if result {
print("刪除成功")
} else {
print("刪除失敗")
}
}
}
}
SQLManager.swift:
// 數(shù)據(jù)庫名稱
private let dbName = "dataSources.db"
class SQLManager {
// 全局訪問點
static let sharedTools: SQLManager = SQLManager()
// 隊列方式
let queue: FMDatabaseQueue
// 構(gòu)造函數(shù)
private init(){
// 打開數(shù)據(jù)庫
// 獲取路徑
let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent(dbName)
// 隊列方式
queue = FMDatabaseQueue(path: path)
// 創(chuàng)建表
createTable()
// 打印路徑
print(path)
}
// MARK: - 創(chuàng)建表
private func createTable() -> Void {
// 獲取文件
let file = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)!
// 準備sql
let sql = try! String(contentsOfFile: file)
// 執(zhí)行sql
queue.inDatabase { (db) in
let result = db.executeStatements(sql)
if result {
print("創(chuàng)建表成功")
} else {
print("創(chuàng)建表失敗")
}
}
}
}
創(chuàng)建表的SQL語句放在單獨的文件db.sql中:
-- 創(chuàng)建個人表 --
CREATE TABLE IF NOT EXISTS "T_Person" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" TEXT,
"age" INTEGER,
"height" REAL
);
-- 創(chuàng)建圖書表 --
CREATE TABLE IF NOT EXISTS "T_Book" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"bookName" TEXT
);