iOS-Swift 数据库 WCDB 二次封装使用/自定义字段映射类型

WCDB官方使用文档

WCDB简介

WCDB 是一个易用、高效、完整的移动数据库框架,它基于 SQLite 和 SQLCipher 开发,在微信中应用广泛,且支持在 C++、Java、Kotlin、Swift、Objc 五种语言环境中使用。

整体架构:

对于WCDB详细的介绍和使用请移步官方文档,本篇文章主要是对WCDB 常用的功能进行二次封装,使数据库的操作更方便一些。还有就是对于自定义映射类型的详细使用,作为官方文档在这块的一个补充。

安装
其它方式安装

通过 Cocoapods 安装

复制代码
    pod 'WCDB.swift'

二次封装

DBmanager

c 复制代码
import Foundation
import WCDBSwift

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

//表名
enum DBTableName : String {
    case userTable = "userTable"
}

class DBmanager{
    static let share = DBmanager.init()
    var db: Database?
    init() {
        db = createDB()
        createTable()
    }
    
    private func createDB() -> Database {
        return Database(at: WcdbDataPath.basePath)
    }
    
    /// 数据库与表的初始化
    private func createTable() {
        do {
            //1. 创建主数据库main的相关表
            try db?.run(transaction: { _ in
                self.createTable(table: DBTableName.userTable, modelType: UserModel.self)
            })
            
        } catch let error {
            debugPrint("初始化数据库及ORM对应关系建立失败\(error.localizedDescription)")
        }
    }
    
    
    ///创建表
    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)
        }
    }
    
    ///插入数据
    public func inser<T: TableEncodable>(objects:[T], intoTable table: DBTableName){
        do {
            try db?.insert(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
    }
    
    ///删除数据表
    func dropTable(table: DBTableName) -> Void {
        do {
            try db?.drop(table: table.rawValue)
        } catch let error {
            debugPrint("drop table error \(error)")
        }
    }
    
    /// 删除所有与该数据库相关的文件
    func removeDbFile() -> Void {
        do {
            try db?.close(onClosed: {
                try self.db?.removeFiles()
            })
        } catch let error {
            debugPrint("not close db \(error)")
        }
    }
}

使用

新建一张表

  1. 在枚举中新增表名
c 复制代码
//表名
enum DBTableName : String {
    case userTable = "userTable"
}
  1. 新建model
    示例model
c 复制代码
import Foundation
import WCDBSwift

final class UserModel: TableCodable {
 
    var id: Int = 0
    var name: String = ""
    var height: Double = 0.0
      
    enum CodingKeys: String, CodingTableKey {
        typealias Root = UserModel
        static let objectRelationalMapping = TableBinding(CodingKeys.self)
        case id
        case name
        case height
    }
    
}
  1. 新建表

数据库操作

首先创建数据库对象

c 复制代码
  let commonDB = DBmanager.share

新增

c 复制代码
      let model = UserModel()
        model.id = 1
        model.name = "张三"

commonDB.inser(objects: [model], intoTable: .userTable)

删除

c 复制代码
 commonDB.deleteFromDb(fromTable: .userTable, where: UserModel.Properties.id.is(model.id))

修改

复制代码
// 创建要更新的 UserModel 对象
var userToUpdate = UserModel()
userToUpdate.name = "NewName"
userToUpdate.height = 180.0

// 定义要更新的属性
let propertiesToUpdate = [UserModel.Properties.name, UserModel.Properties.height]

// 构建条件(例如,根据 id 更新)
let updateCondition = UserModel.Properties.id == 1

// 调用 update 方法
commonDB.update(fromTable: .userTable, on: [UserModel.Properties.height], itemModel: userToUpdate,where: updateCondition)

查询

复制代码
if let tempArray:[UserModel] = commonDB.qurey(fromTable: .userTable) {
            userArray = tempArray
        }

自定义字段映射类型

自定义字段映射类型文档

示例

复制代码
import Foundation
import WCDBSwift

final class UserModel: TableCodable {
 
    var id: Int = 0
    var name: String = ""
    var height: Double = 0.0
    var address: addressModel?
    
    enum CodingKeys: String, CodingTableKey {
        typealias Root = UserModel
        static let objectRelationalMapping = TableBinding(CodingKeys.self)
        case id
        case name
        case height
        case address
    }
    
}

//自定义字段映射类型
class addressModel: ColumnCodable {
    
    required init() {}
    
    var home:String = ""
    var company:String = ""

    static var columnType: ColumnType {
           return .BLOB
       }
    
    required init?(with value: WCDBSwift.Value) {
        let data = value.dataValue
        guard data.count > 0,
              let jsonDict = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
            return nil
        }
        
        guard let home = jsonDict["home"] as? String else {
            return nil
        }
        guard let company = jsonDict["company"] as? String else {
            return nil
        }
        
        self.home = home
        self.company = company
    }
    
    func archivedValue() -> WCDBSwift.Value {
        var jsonDict: [String: Any] = [:]
        jsonDict["home"] = home
        jsonDict["company"] = company
        guard let data = try? JSONSerialization.data(withJSONObject: (jsonDict as NSDictionary), options: []) else {
            return FundamentalValue.init()
        }
        
        return FundamentalValue.init(data)
    }
    
}

结语

以上便是WCDB Swift 版本的基本使用,本篇旨在帮你快速的上手使用WCDB来完成数据库的基础操作。如需其它高级的数据库操作,请移步到官方文档。

WCDB仓库地址
WCDB官方文档直通车


感谢您的阅读和参与,HH思无邪愿与您一起在技术的道路上不断探索。如果您喜欢这篇文章,不妨留下您宝贵的赞!如果您对文章有任何疑问或建议,欢迎在评论区留言,我会第一时间处理,您的支持是我前行的动力,愿我们都能成为更好的自己!

相关推荐
萤虫之光43 分钟前
【iOS】PrivacyInfo.xcprivacy隐私清单文件(二)
ios
nongcunqq1 小时前
abap 操作 excel
java·数据库·excel
rain bye bye1 小时前
calibre LVS 跑不起来 就将setup 的LVS Option connect下的 connect all nets by name 打开。
服务器·数据库·lvs
YGGP2 小时前
【Swift】LeetCode 1. 两数之和
swift
阿里云大数据AI技术3 小时前
云栖实录|MaxCompute全新升级:AI时代的原生数据仓库
大数据·数据库·云原生
不剪发的Tony老师3 小时前
Valentina Studio:一款跨平台的数据库管理工具
数据库·sql
巴博尔3 小时前
uniapp的IOS中首次进入,无网络问题
前端·javascript·ios·uni-app
weixin_307779134 小时前
在 Microsoft Azure 上部署 ClickHouse 数据仓库:托管服务与自行部署的全面指南
开发语言·数据库·数据仓库·云计算·azure
六元七角八分4 小时前
pom.xml
xml·数据库
虚行4 小时前
Mysql 数据同步中间件 对比
数据库·mysql·中间件