1.封装的一个不用写sqlite语句的数据库类,使用的是swift4.0,运用了runtime机制获取属性名,和属性值,通过模型直接调用方法就可以进行数据库操作,先看看效果图
2.先对封装的类进行简单的介绍
2-1. 对QYPSQLiteManager内代码
import Foundation
import FMDB
class QYPSQLiteManager{
static let shared = QYPSQLiteManager()
var db = FMDatabase()
var queue = FMDatabaseQueue()
init() {
let dbName = "status.db"
var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
path = (path as NSString).appendingPathComponent(dbName)
print("数据库的路径 " + path)
// 1 .使用FMDatabaseQueue
queue = FMDatabaseQueue(path: path)
}
}
2-2. QYPObject+Extension
import Foundation
extension NSObject{
/// 创建数据表
func createTable(arr:[String]) {
var sql = "create table if not exists \(self.classForCoder) (id integer primary key autoincrement"
for str in arr {
sql += ",\(str) text"
}
sql += ");"
// 2. 执行 SQL - FMDB 的内部队列,串行队列,同步执行
// 可以保证同一时间,只有一个任务操作数据库,从而保证数据库的读写安全!
QYPSQLiteManager.shared.queue.inDatabase { (db) in
// 只有在创表的时候,使用执行多条语句,可以一次创建多个数据表
// 在执行增删改的时候,一定不要使用 statements 方法,否则有可能会被注入!
if db.executeStatements(sql) == true {
print("创表成功")
} else {
print("创表失败")
}
}
}
/// 查询数据表是否存在
func tableViewIsExists() -> Bool{
let isTableOkSql = "select count(*) as 'count' from sqlite_master where type ='table' and name = '\(self.classForCoder)';"
var tempCount:Int64 = 0
// 判断表是否已经存在
QYPSQLiteManager.shared.queue.inDatabase { (db) in
guard let rs = db.executeQuery(isTableOkSql, withArgumentsIn: []) else {
return
}
while rs.next() {
tempCount = Int64(rs.int(forColumn: "count"))
}
}
if tempCount == 0{
return false
}
return true
}
}
2-3 *这里是我们需要使用的接口QYPDBApi类
import Foundation
extension NSObject {
/// 插入数据
func insertData(){
var insertSql = "insert into \(self.classForCoder)"
let arr = self.propertyList()
var key = " ("
var values = " values("
for str in arr {
key += "\(str),"
values += "?,"
}
key.remove(at:key.index(before: key.endIndex))
values.remove(at:values.index(before: values.endIndex))
insertSql += key + ")" + values + ");"
let valuesArr = self.getValueOfProperty()
QYPSQLiteManager.shared.queue.inTransaction { (db, rollback) in
// 执行 SQL
if db.executeUpdate(insertSql, withArgumentsIn: valuesArr) == false {
// 回滚
rollback.pointee = true
print("插入数据失败")
}else{
print("插入数据成功")
}
}
}
/// 删除数据
///
/// - Parameter deletStr: "name = 'jacob'"
func delete(deletStr:String){
let deleteSql = "delete from \(self.classForCoder) where \(deletStr);"
print(deleteSql)
QYPSQLiteManager.shared.queue.inDatabase { (db) in
if db.executeUpdate(deleteSql, withArgumentsIn: []) == true {
print("\(self.classForCoder)表删除了\(db.changes)条记录")
}else {
print("\(self.classForCoder)表数据操作失败")
}
}
}
/// 跟新语句全部模型里面的数据全部跟新
func updateData(whereStr:String){
/// 定义的属性
var updateSql = "UPDATE \(self.classForCoder) SET"
/// 获取到的模型的属性名
let columnArr = self.propertyList()
/// 获取到的模型的属性值
let valueArr = self.getValueOfProperty()
for i in 0.." \(columnArr[i]) = '\(valueArr[i])',"
}
updateSql.remove(at:updateSql.index(before: updateSql.endIndex))
updateSql += " WHERE \(whereStr);"
print(updateSql)
QYPSQLiteManager.shared.queue.inDatabase { (db) in
if db.executeUpdate(updateSql, withArgumentsIn: []) == true {
print("\(self.classForCoder)改变了\(db.changes)条记录")
}else {
print("\(self.classForCoder)表数据操作失败")
}
}
}
/// 表中数据全部查出默认按升序排列
// FIXME:先放在这里,还未处理的是 ORDER BY id DESC 别的东西,现在只做到了id的降序排列
func selectData(whereStr:String,ORDER_BY:String = "id ASC") -> [[String:AnyObject]]{
var selectSql = "SELECT id,"
let columnArr = self.propertyList()
for str in columnArr {
selectSql += " \(str),"
}
selectSql.remove(at:selectSql.index(before: selectSql.endIndex))
selectSql += " FROM \(self.classForCoder) WHERE \(whereStr) ORDER BY \(ORDER_BY);"
print(selectSql)
var result = [[String: AnyObject]]()
QYPSQLiteManager.shared.queue.inDatabase { (db) in
guard let rs = db.executeQuery(selectSql, withArgumentsIn: []) else {
return
}
while rs.next() {
// FIXME:这里还想到好的办法将其以模型数组的形式return
// 这里先以字典数组的形式返回回去吧!
// let myClass = self.classForCoder
// 列数
var dic = [String:AnyObject]()
let colCount = rs.columnCount
for col in 0..let name = rs.columnName(for: col),
let value = rs.object(forColumnIndex: col) else {
continue
}
// 在这里通过运行时给类添加属性,并且设置属性值
dic[name] = value as AnyObject
}
result.append(dic)
}
}
return result
}
}
2-4…这里是runtime获取属性值,和属性名
import Foundation
extension NSObject{
/// 通过字典设置属性值
///
/// - Parameter dic: [属性名:属性值]
/// - Returns: 是否设置成功
func setValueOfProperty(dic:[String:String])->Bool{
let allPropertys = self.propertyList()
for key in allPropertys {
self.setValue(dic[key], forKey: key)
}
return true
}
/// 获取属性值
///
/// - Returns: 返回获取到的属性值数组
func getValueOfProperty()->[String]{
let allPropertys = self.propertyList()
var values = [String]()
for key in allPropertys {
let val = self.value(forKey: key) as? String ?? ""
values.append(val)
}
return values
}
///[使用运行时]获取当前类所有的属性数组
func propertyList() -> [String] {
var count :UInt32 = 0
//获取‘类’的属性列表
guard let list = class_copyPropertyList(self.classForCoder, &count) else{
return []
}
var arr = [String]()
for i in 0..//根据下标 获取属性
let a = list[i]
//获取属性的名称
let cName = property_getName(a)
let n = String(utf8String:cName)
arr.append(n ?? "")
}
// 在这个方法里面创建数据表.
if tableViewIsExists() == false{
createTable(arr: arr)
}
return arr
}
}
4.*同时项目运用了MVVM的使用,基本上和实际项目模式一直,可以值得借鉴
5.介绍结束.完整的代码已经提交github地址
https://github.com/13670242169/QYPSQLFMDBManager.git
要是可以帮到大伙,求点赞,要是哪里写的不足,求指教