let path =NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask,true)[0]
//如果路径为空
// 1.一个文件的系统路径。磁盘中可以不存在此文件,因为如果不存在会自动为你创建。
// 2.一个空的字符串 @""。会在临时位置创建一个空的数据库,当 FMDatabase连接关闭时,该数据库会被删除。
// 3.NULL。会在内存中创建一个数据库,当 FMDatabase连接关闭时,该数据库会被销毁。
let filePath = path.stringByAppendingString("/zj.mydb")
mainDatabase =FMDatabaseQueue(path: filePath)
mainDatabase?.inTransaction({ (db, rollback)in
//创建表
let sql ="create table if not exists myTable1(bookId integer primary key autoincrement, bookName text,description text)"
let result = db?.executeStatements(sql)
if result ==true {
print("创建表成功")
} else {
rollback.memory =true
}
})
//使用事务可以保证线程安全插入操作
mainDatabase?.inTransaction{ (db, rollback)in
do {
//插入数据
let insertSql ="insert into myTable1 (bookName,description) values(?,?)"
let insertResult = db?.executeUpdate(insertSql, withArgumentsInArray: ["斗破苍穹2","炎帝消炎2"])
if insertResult ==true {
print("插入成功")
} else {
print("插入失败")
}
} catch {
rollback.memory =true
print(error)
}
}
//删除数据操作
mainDatabase?.inTransaction({ (db, rollback)in
do {
let deleteSql ="delete from myTable1 where bookName like ?"
try db.executeUpdate(deleteSql, values: ["斗破苍穹"])
} catch {
rollback.memory =true
print(error)
}
})
//更新数据
mainDatabase?.inTransaction({ (db, rollback)in
do {
let updateSql ="update myTable1 set bookName = ? where description = ?"
try db.executeUpdate(updateSql, values: ["斗破苍穹1","炎帝消炎2"])
} catch {
rollback.memory =true
print(error)
}
})
//查询数据
mainDatabase?.inTransaction({ (db, rollback)in
do {
let selectSql ="select * from myTable1"
let result =try db.executeQuery(selectSql, values:nil)
while result.next() {
let name = result.stringForColumn("bookName")
let des = result.stringForColumn("description")
print(name,des)
}
} catch {
rollback.memory =true
print(error)
}
})
}