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)")
}
}
}
使用
新建一张表
- 在枚举中新增表名
c
//表名
enum DBTableName : String {
case userTable = "userTable"
}
- 新建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
}
}
- 新建表
数据库操作
首先创建数据库对象
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来完成数据库的基础操作。如需其它高级的数据库操作,请移步到官方文档。
感谢您的阅读和参与,HH思无邪愿与您一起在技术的道路上不断探索。如果您喜欢这篇文章,不妨留下您宝贵的赞!如果您对文章有任何疑问或建议,欢迎在评论区留言,我会第一时间处理,您的支持是我前行的动力,愿我们都能成为更好的自己!