class HMSQLiteTools: NSObject {
//使用單例對象
static let shared: HMSQLiteTools = HMSQLiteTools()
//創(chuàng)建數(shù)據(jù)庫文件 并l且打開數(shù)據(jù)庫連接
//單例對象一旦創(chuàng)建的時候就打開數(shù)據(jù)
//必須有值
let queue: FMDatabaseQueue
override init() {
//數(shù)據(jù)庫文件存儲在沙盒路徑中
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("weibo.db")
//如果數(shù)據(jù)庫不存在就創(chuàng)建數(shù)據(jù)庫并且打開連接,如果存在就直接打開連接
queue = FMDatabaseQueue(path: path)
print(path)
super.init()
//初始化的時候就創(chuàng)建對應(yīng)的數(shù)據(jù)表
createTable()
}
private func createTable() {
let sql = "CREATE TABLE IF NOT EXISTS T_Status (statusId INTEGER PRIMARY KEY NOT NULL, status TEXT, userId TEXT, create_date TEXT DEFAULT (datetime('now','localtime')));"
//使用queue中數(shù)據(jù)庫操作的核心對象來執(zhí)行sql語句
queue.inTransaction { (db, rollback) in
//rollback 如果操作失敗就執(zhí)行回滾的操作
let res = db!.executeStatements(sql)
if res {
print("建表成功")
} else {
print("失敗")
//執(zhí)行回滾
rollback?.pointee = true
}
}
}
}