?? 使用的類最好導(dǎo)入 import WCDBSwift 拐邪,否則會報錯
pod 'WCDB.swift'
import WCDBSwift
創(chuàng)建一個model,遵循 TableCodable 協(xié)議
class HealthModel :TableCodable{
var userID : String?
var titleName: String?
var carNumber: String?
var icon: String?
required init() {}
enum CodingKeys: String, CodingTableKey {
typealias Root = HealthModel
////列出應(yīng)綁定到表的屬性
case userID
case titleName
case carNumber
case icon
static let objectRelationalMapping = TableBinding(CodingKeys.self)
/*
ColumnConstraintBinding(
isPrimary: Bool = false, // 該字段是否為主鍵蜒谤。字段約束中只能同時存在?個主鍵
orderBy term: OrderTerm? = nil, // 當(dāng)該字段是主鍵時,存儲順序是升序還是降序
isAutoIncrement: Bool = false, // 當(dāng)該字段是主鍵時晶渠,其是否?持?增罕伯。只有整型數(shù)據(jù)可以定義為?增曲伊。
onConflict conflict: Conflict? = nil, // 當(dāng)該字段是主鍵時,若產(chǎn)?沖突追他,應(yīng)如何處理
isNotNull: Bool = false, // 該字段是否可以為空
isUnique: Bool = false, // 該字段是否可以具有唯?性
defaultTo defaultValue: ColumnDef.DefaultType? = nil // 該字段在數(shù)據(jù)庫內(nèi)使?什么默認(rèn)值
*/
//主鍵坟募、唯一、不為null邑狸、默認(rèn)值等的列約束懈糯。它是可選的。
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()
/// 數(shù)據(jù)庫
public var database: Database?
/// 數(shù)據(jù)庫名稱,每個用戶一個數(shù)據(jù)庫
private var dbName: String {
get {
return "登陸的用戶userID" + ".sqlite"
}
}
private init() { }
// MARK: - Public
/// 連接數(shù)據(jù)庫
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("數(shù)據(jù)庫路徑: ", fileURL.path)
database = Database(withFileURL: fileURL)
// 數(shù)據(jù)庫建表
createTables()
}
/// 關(guān)閉數(shù)據(jù)庫
public func closeDatabase() {
database?.close()
database = nil
}
// MARK: - Private
/// 建表
///要多少表創(chuàng)建多少表
//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)
}
/// 查對象數(shù)組
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
}
// 聯(lián)表
func prepareMultiSelect (on: [PropertyConvertible], fromTables:[String]) -> WCDBSwift.MultiSelect?
{
return try? database?.prepareMultiSelect(on: on, fromTables: fromTables) ?? nil
}
}
使用 增刪改查单雾,條件語句
條件 :
以456開頭 like("456%"))
包含456 like("%456%")
相等 is
增
//默認(rèn)創(chuàng)建幾組數(shù)據(jù)
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 == id))
改 HealthModel.Properties.all 或 [HealthModel.Properties.指定字段]
WCDBUtil.share.update(HealthModel_Name, on:HealthModel.Properties.all, with: model, where: HealthModel.Properties.userID == id)
查
WCDBUtil.share.getObjects(HealthModel_Name)
// 接受
let arr: [HealthModel] = WCDBUtil.share.getObjects(HealthModel_Name)