Swift WCDB 使用

作者: 9岁就很6 | 来源:发表于2022-06-01 17:41 被阅读0次

pod 'WCDB.swift'
import WCDBSwift
创建一个model,遵循 TableCodable 协议

class HealthModel :TableCodable{
    
    var userID : String?
    var titleName: String?
    var carNumber: String?
    var icon: String?
    
    required init() {}

    enum CodingKeys: String, CodingTableKey {
        
        typealias Root = HealthModel
        ////列出应绑定到表的属性
        case userID
        case titleName
        case carNumber
        case icon
        
        static let objectRelationalMapping = TableBinding(CodingKeys.self)
      /*
       ColumnConstraintBinding(
           isPrimary: Bool = false, // 该字段是否为主键。字段约束中只能同时存在⼀个主键
           orderBy term: OrderTerm? = nil, // 当该字段是主键时,存储顺序是升序还是降序
           isAutoIncrement: Bool = false, // 当该字段是主键时,其是否⽀持⾃增。只有整型数据可以定义为⾃增。
           onConflict conflict: Conflict? = nil, // 当该字段是主键时,若产⽣冲突,应如何处理
           isNotNull: Bool = false, // 该字段是否可以为空
           isUnique: Bool = false, // 该字段是否可以具有唯⼀性
           defaultTo defaultValue: ColumnDef.DefaultType? = nil // 该字段在数据库内使⽤什么默认值
       
       */
        //主键、唯一、不为null、默认值等的列约束。它是可选的。
        static var columnConstraintBindings: [CodingKeys: ColumnConstraintBinding]? {
            return [
                //主键
                .userID: ColumnConstraintBinding(isPrimary: true, isAutoIncrement: false),
            ]
        }
    }
    
    //Properties below are needed only the primary key is auto-incremental
    var isAutoIncrement: Bool = false
    var lastInsertedRowID: Int64 = 0
    
}

WCDB的封装(WCDBUtil)

mport Foundation
import WCDBSwift
import KakaJSON

class WCDBUtil {
    
    static let share = WCDBUtil()
    
    /// 数据库
    public var database: Database?
    /// 数据库名称,每个用户一个数据库
    private var dbName: String {
        get {
             return "登陆的用户userID"  + ".sqlite" 
        }
    }
    
    private init() { }
    
    // MARK: - Public
    
    /// 连接数据库
    public func connectDatabase() {
        
        if database != nil {
            database?.close()
        }
        
        guard let fileURL = try? FileManager.default
                .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
                .appendingPathComponent(dbName) else { return }
        
        debugPrint("数据库路径: ", fileURL.path)
        
        database = Database(withFileURL: fileURL)
        
        // 数据库建表
        createTables()
    }
    
    /// 关闭数据库
    public func closeDatabase() {
        database?.close()
        database = nil
    }
    
    // MARK: - Private
    
    /// 建表
    ///要多少表创建多少表
    //HealthModel_Name 表名
   // HealthModel.self 对象model
    private func createTables() {
        try? database?.create(table: HealthModel_Name, of: HealthModel.self)
        try? database?.create(table: recordDietModel_Name, of: recordDietModel.self)
         
    }
    
}

extension WCDBUtil {

    /// 增
    func insert<T: TableCodable>(_ objects: [T], tableName: String) {
        try? database?.insert(objects: objects, intoTable: tableName)
    }
    
    func insertOrReplace<T: TableCodable>(_ objects: [T], _ property:[PropertyConvertible]?, tableName: String) {
        try? database?.insertOrReplace(objects: objects, on: property, intoTable: tableName)
    }
    
    /// 删
    func delete(
        _ tableName: String,
        where condition: Condition? = nil,
        orderBy orderList: [OrderBy]? = nil,
        limit: Limit? = nil,
        offset: Offset? = nil)
    {
        try? database?.delete(fromTable: tableName, where: condition, orderBy: orderList, limit: limit, offset: offset)
    }
    
    /// 改, 使用TableCodable
    func update<T: TableCodable>(
        _ tableName: String,
        on propertyConvertibleList: [PropertyConvertible],
        with object: T,
        where condition: Condition? = nil,
        orderBy orderList: [OrderBy]? = nil,
        limit: Limit? = nil,
        offset:Offset? = nil)
    {
      
        try? database?.update(table: tableName,
                              on: propertyConvertibleList,
                              with: object,
                              where: condition,
                              orderBy: orderList,
                              limit: limit,
                              offset: offset)
    }
    
    /// 改, 使用ColumnEncodable
    func update(
        _ tableName: String,
        on propertyConvertibleList: PropertyConvertible...,
        with row: [ColumnEncodable],
        where condition: Condition? = nil,
        orderBy orderList: [OrderBy]? = nil,
        limit: Limit? = nil,
        offset:Offset? = nil)
    {
        try? database?.update(table: tableName, on: propertyConvertibleList, with: row, where: condition, orderBy: orderList, limit: limit, offset: offset)
    }
    
    ///修改
    func update<T: TableEncodable>( on propertyConvertibleList: PropertyConvertible..., itemModel object:T,where condition: Condition? = nil){
             try? database?.update(table: "\(T.self)", on: propertyConvertibleList, with: object, where: condition)
       }
    
    
    
    
    /// 查对象数组
    func getObjects<T: TableCodable>(
        _ tableName: String,
        where condition: Condition? = nil,
        orderBy orderList: [OrderBy]? = nil,
        limit: Limit? = nil,
        offset: Offset? = nil) -> [T]?
    {
        let objects: [T]? = try? database?.getObjects(fromTable: tableName, where: condition, orderBy: orderList, limit: limit, offset: offset)
        return objects
    }
    
    /// 查单个对象
    func getObject<T: TableCodable>(
        _ tableName: String,
        where condition: Condition? = nil,
        orderBy orderList: [OrderBy]? = nil,
        offset: Offset? = nil) -> T?
    {
        let object: T? = try? database?.getObject(fromTable: tableName, where: condition, orderBy: orderList, offset: offset)
        return object
    }

    // 联表
    func prepareMultiSelect (on: [PropertyConvertible], fromTables:[String]) -> WCDBSwift.MultiSelect?
    {
        return try? database?.prepareMultiSelect(on: on, fromTables: fromTables) ?? nil
    }
    
}

使用 增删改查,条件语句
条件 :
以456开头 like("456%"))
包含456 like("%456%")
相等 is

 //默认创建几组数据
            var modelArr : [HealthModel] = []
            let dataArray = [
                             ["title":"多喝水","icon":"icon","carNumber":"8"],
                             ["title":"早起","icon":"icon","carNumber":"1",],
                             ["title":"早睡","icon":"icon","carNumber":"1",],
                             ["title":"早餐","icon":"icon","carNumber":"1",],
                             ["title":"午餐","icon":"icon","carNumber":"1",],
                             ["title":"晚餐","icon":"icon","carNumber":"1",]
            ]
            for (index,dataDic) in dataArray.enumerated() {
                let dataModel = HealthModel()
                dataModel.carNumber = dataDic["carNumber"]
                dataModel.titleName = dataDic["title"]
                dataModel.icon = dataDic["icon"]
                dataModel.userID = "100086+\(index)"
                modelArr.append(dataModel)
            }
            WCDBUtil.share.insert(modelArr, tableName: HealthModel_Name)

 WCDBUtil.share.delete(HealthModel_Name, where: HealthModel.Properties.userID.is(id))
            

改 HealthModel.Properties.all 或 [HealthModel.Properties.指定字段]

WCDBUtil.share.update(HealthModel_Name, on:HealthModel.Properties.all,    with: model,    where: HealthModel.Properties.userID.is(id))

 WCDBUtil.share.getObjects(HealthModel_Name) 
            

// 接受
let arr: [HealthModel] = WCDBUtil.share.getObjects(HealthModel_Name) 
            

相关文章

网友评论

    本文标题:Swift WCDB 使用

    本文链接:https://www.haomeiwen.com/subject/zuvxmrtx.html