美文网首页
## WCDBSwift 的简单使用与封装

## WCDBSwift 的简单使用与封装

作者: 秋叶红90 | 来源:发表于2021-04-15 01:32 被阅读0次

    WCDBSwift 的简单使用与封装

    模型例子

    import WCDBSwift
    import UIKit
    class SHSongModel: TableCodable {
        
        
    //    /// 歌名字
        var name:String = ""
    //
    //    /// 作者
        var author:String = ""
    //
    //    /// 歌词链接 可以是网络也可以是本地
        var lrclink:String = ""
    //    /// 可以是网络也可以是本地
        var file_link:String = ""
    //    /// 图片封面
        var pic:String = "12.jpg"
        
        
        enum CodingKeys:String, CodingTableKey {
            typealias Root = SHSongModel
            case name
            case author
            case lrclink
            case file_link
            case pic
    
            
            static let objectRelationalMapping = TableBinding(CodingKeys.self)
        }
        
        
    //    enum CodingKeys: String, CodingTableKey {
    //        typealias Root = SHSongModel
    //
    //        //List the properties which should be bound to table
    //        case name
    //        case song_id
    //        case author
    //        case lrclink
    //        case file_link
    //        case pic
    //
    //        static let objectRelationalMapping = TableBinding(CodingKeys.self)
    //
    //        //Column constraints for primary key, unique, not null, default value and so on. It is optional.
    //        //static var columnConstraintBindings: [CodingKeys: ColumnConstraintBinding]? {
    //        //    return [
    //        //        .variable: ColumnConstraintBinding(isPrimary: true, isAutoIncrement: true),
    //        //        .variable2: ColumnConstraintBinding(isUnique: true)
    //        //    ]
    //        //}
    //
    //        //Index bindings. It is optional.
    //        //static var indexBindings: [IndexBinding.Subfix: IndexBinding]? {
    //        //    return [
    //        //        "_index": IndexBinding(indexesBy: CodingKeys.variable2)
    //        //    ]
    //        //}
    //
    //        //Table constraints for multi-primary, multi-unique and so on. It is optional.
    //        //static var tableConstraintBindings: [TableConstraintBinding.Name: TableConstraintBinding]? {
    //        //    return [
    //        //        "MultiPrimaryConstraint": MultiPrimaryBinding(indexesBy: variable2.asIndex(orderBy: .descending), variable3.primaryKeyPart2)
    //        //    ]
    //        //}
    //
    //        //Virtual table binding for FTS and so on. It is optional.
    //        //static var virtualTableBinding: VirtualTableBinding? {
    //        //    return VirtualTableBinding(with: .fts3, and: ModuleArgument(with: .WCDB))
    //        //}
    //    }
        
        func getBy(author:String)->[SHSongModel]? {
            
            let arr:[SHSongModel]? = DBManager.share.qurey(where: SHSongModel.Properties.author == author, orderBy: [SHSongModel.Properties.author.asOrder(by: OrderTerm.ascending)])
            
            return arr
        }
    }
    
    
    

    DBManager 创建数据库管理

    import WCDBSwift
    import UIKit
    struct WcdbDataPath {
        
       static let basePath =  NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/DB/wcdb.db"
    }
    
    class DBManager: NSObject {
        
        static let share = DBManager.init()
        var db: Database?
        
        override init() {
            super.init()
    
            db = createDB()
            createTable()
        }
        
        private func createDB() -> Database {
           return Database(withPath: WcdbDataPath.basePath)
        }
        
        /// 数据库与表的初始化
        private func createTable() {
            do {
             //1. 创建主数据库main的相关表
               try db?.run(transaction: {
                    createTable( modelType: SHSongModel.self)
                
                })
             
            } catch let error {
                print("初始化数据库及ORM对应关系建立失败\(error.localizedDescription)")
            }
        }
    
        ///创建表
        private func createTable<T: TableDecodable>(modelType: T.Type) {
            do {
                print("jj_\(modelType.self)")
                try db?.create(table: "\(modelType.self)", of: modelType)
            }catch let error {
                debugPrint("error \(error.localizedDescription)")
            }
        }
        
        ///插入数据
        public func inser<T: TableEncodable>(objects:[T],modelType: T.Type){
            do {
                print("---\(T.self)")
                print("mm___\(modelType.self)")
                try db?.insert(objects: objects, intoTable: "\(T.self)")
            }catch let error {
                debugPrint(error.localizedDescription)
            }
        }
    
        ///修改
        public func update<T: TableEncodable>( on propertys:[PropertyConvertible], itemModel object:T,where condition: Condition? = nil){
            do {
                try db?.update(table: "\(T.self)", on: propertys, with: object, where: condition)
            } catch let error {
                debugPrint(" update obj error \(error.localizedDescription)")
            }
        }
    
        ///删除
        public func deleteFromDb<T: TableEncodable>( modelType:T.Type,where condition: Condition? = nil){
            do {
                try db?.delete(fromTable: "\(modelType.self)", where:condition)
            } catch let error {
                debugPrint("delete error \(error.localizedDescription)")
            }
        }
    
        ///查询
        public func qurey<T: TableDecodable>( where condition: Condition? = nil, orderBy orderList:[OrderBy]? = nil) -> [T]? {
            do {
                let allObjects: [T] = try (db?.getObjects(fromTable: "\(T.self)", where:condition, orderBy:orderList))!
                debugPrint("\(allObjects)");
                return allObjects
            } catch let error {
                debugPrint("no data find \(error.localizedDescription)")
            }
            return nil
        }
        
        ///删除数据表
        func dropTable<T: TableEncodable>(modelType:T.Type) -> Void {
            do {
                try db?.drop(table: "\(modelType.self)")
            } catch let error {
                debugPrint("drop table error \(error)")
            }
        }
        
        /// 删除所有与该数据库相关的文件
        func removeDbFile() -> Void {
            do {
                try db?.close(onClosed: {
                    try db?.removeFiles()
                })
            } catch let error {
                debugPrint("not close db \(error)")
            }
            
        }
       
    }
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:## WCDBSwift 的简单使用与封装

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