swift 數(shù)據(jù)庫WCDB封裝使用 (2020.04.17) 一行代碼實現(xiàn)增刪改查

wcdb github 地址 這里面有詳細的安裝使用說明文檔, 超級無敵詳細那種.

附上我的swfit項目, 項目里面有整個swift應(yīng)用使用框架, 網(wǎng)絡(luò)請求框架, DSBridge原生與H5交互的用法, 反射知識的使用, WCDB數(shù)據(jù)庫的封裝使用, WebRTC音視頻直播demo, socket的使用, socket協(xié)議的封裝使用等等知識點. 希望對大家有用.-->swfit完整項目2020持續(xù)更新完善

安裝

使用cocoapod進行安裝, 超級方便

pod 'WCDB.swift'

WCDB支持ORM(直接對模型對象進行操作), 例如我們要存一個Sample對象到數(shù)據(jù)庫:


import WCDBSwift

class Sample: NSObject,TableCodable {
    
    var id: Int = 0
    var ssid: String?
    var password: String?

    enum CodingKeys: String, CodingTableKey {
        typealias Root = Sample
        static let objectRelationalMapping = TableBinding(CodingKeys.self)

        case id
        case ssid
        case password
        
        //Column constraints for primary key, unique, not null, default value and so on. It is optional.
        static var columnConstraintBindings: [CodingKeys: ColumnConstraintBinding]? {
            return [
                //自增主鍵的設(shè)置
                .id: ColumnConstraintBinding(isPrimary: true, isAutoIncrement: true)
            ]
        }

    }
    
    /// 用于定義是否使用自增的方式插入
    var isAutoIncrement: Bool = true
    
    /// 用于獲取自增插入后的主鍵值
    var lastInsertedRowID: Int64 = 0
}

封裝的數(shù)據(jù)庫管理工具類:

import WCDBSwift


struct WcdbDataPath {
    
   static let basePath =  NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/DB/wcdb.db"
}
enum DBTableName : String {

    case sampleTable = "Sample"
}

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)
    }
    
    /// 數(shù)據(jù)庫與表的初始化
    private func createTable() {
        do {
         //1. 創(chuàng)建主數(shù)據(jù)庫main的相關(guān)表
           try db?.run(transaction: {
            createTable(table: DBTableName.sampleTable, modelType: Sample.self)
            })
         
        } catch let error {
            print("初始化數(shù)據(jù)庫及ORM對應(yīng)關(guān)系建立失敗\(error.localizedDescription)")
        }
    }

    ///創(chuàng)建表
    private func createTable<T: TableDecodable>(table: DBTableName, modelType: T.Type) {
        do {
            try db?.create(table: table.rawValue, of: modelType)
        }catch let error {
            debugPrint(error.localizedDescription)
        }
    }
    
    ///插入數(shù)據(jù)
    public func inser<T: TableEncodable>(objects:[T], intoTable table: DBTableName){
        do {
            try db?.insert(objects: objects, intoTable: table.rawValue)
        }catch let error {
            debugPrint(error.localizedDescription)
        }
    }

    ///修改
    public func update<T: TableEncodable>(fromTable table: DBTableName, on propertys:[PropertyConvertible], itemModel object:T,where condition: Condition? = nil){
        do {
            try db?.update(table: table.rawValue, on: propertys, with: object, where: condition)
        } catch let error {
            debugPrint(" update obj error \(error.localizedDescription)")
        }
    }

    ///刪除
    public func deleteFromDb(fromTable table: DBTableName, where condition: Condition? = nil){
        do {
            try db?.delete(fromTable: table.rawValue, where:condition)
        } catch let error {
            debugPrint("delete error \(error.localizedDescription)")
        }
    }

    ///查詢
    public func qurey<T: TableDecodable>(fromTable table: DBTableName, where condition: Condition? = nil, orderBy orderList:[OrderBy]? = nil) -> [T]? {
        do {
            let allObjects: [T] = try (db?.getObjects(fromTable: table.rawValue, where:condition, orderBy:orderList))!
            debugPrint("\(allObjects)");
            return allObjects
        } catch let error {
            debugPrint("no data find \(error.localizedDescription)")
        }
        return nil
    }
    
    ///刪除數(shù)據(jù)表
    func dropTable(table: DBTableName) -> Void {
        do {
            try db?.drop(table: table.rawValue)
        } catch let error {
            debugPrint("drop table error \(error)")
        }
    }
    
    /// 刪除所有與該數(shù)據(jù)庫相關(guān)的文件
    func removeDbFile() -> Void {
        do {
            try db?.close(onClosed: {
                try db?.removeFiles()
            })
        } catch let error {
            debugPrint("not close db \(error)")
        }
        
    }
   
}

以上是基本的開發(fā)使用功能, 如果需要更多更詳細的封裝使用, 可以參考一下官方文檔[wcdb github 地址](https://github.com/Tencent/wcdb](https://github.com/Tencent/wcdb) 真的超級詳細.
)

完 !

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容