Swift WCDB 使用

?? 使用的類最好導(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) 
            
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末赚哗,一起剝皮案震驚了整個濱河市她紫,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌屿储,老刑警劉巖犁苏,帶你破解...
    沈念sama閱讀 207,248評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異扩所,居然都是意外死亡围详,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,681評論 2 381
  • 文/潘曉璐 我一進(jìn)店門祖屏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來助赞,“玉大人,你說我怎么就攤上這事袁勺”⑹常” “怎么了?”我有些...
    開封第一講書人閱讀 153,443評論 0 344
  • 文/不壞的土叔 我叫張陵期丰,是天一觀的道長群叶。 經(jīng)常有香客問我,道長钝荡,這世上最難降的妖魔是什么街立? 我笑而不...
    開封第一講書人閱讀 55,475評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮埠通,結(jié)果婚禮上赎离,老公的妹妹穿的比我還像新娘。我一直安慰自己端辱,他們只是感情好梁剔,可當(dāng)我...
    茶點故事閱讀 64,458評論 5 374
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著舞蔽,像睡著了一般荣病。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上渗柿,一...
    開封第一講書人閱讀 49,185評論 1 284
  • 那天个盆,我揣著相機與錄音,去河邊找鬼做祝。 笑死砾省,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的混槐。 我是一名探鬼主播,決...
    沈念sama閱讀 38,451評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼轩性,長吁一口氣:“原來是場噩夢啊……” “哼声登!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,112評論 0 261
  • 序言:老撾萬榮一對情侶失蹤悯嗓,失蹤者是張志新(化名)和其女友劉穎件舵,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體脯厨,經(jīng)...
    沈念sama閱讀 43,609評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡铅祸,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,083評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了合武。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片临梗。...
    茶點故事閱讀 38,163評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖稼跳,靈堂內(nèi)的尸體忽然破棺而出盟庞,到底是詐尸還是另有隱情,我是刑警寧澤汤善,帶...
    沈念sama閱讀 33,803評論 4 323
  • 正文 年R本政府宣布什猖,位于F島的核電站,受9級特大地震影響红淡,放射性物質(zhì)發(fā)生泄漏不狮。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,357評論 3 307
  • 文/蒙蒙 一在旱、第九天 我趴在偏房一處隱蔽的房頂上張望荤傲。 院中可真熱鬧,春花似錦颈渊、人聲如沸遂黍。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,357評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽雾家。三九已至,卻和暖如春绍豁,著一層夾襖步出監(jiān)牢的瞬間芯咧,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,590評論 1 261
  • 我被黑心中介騙來泰國打工竹揍, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留敬飒,地道東北人。 一個月前我還...
    沈念sama閱讀 45,636評論 2 355
  • 正文 我出身青樓芬位,卻偏偏與公主長得像无拗,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子昧碉,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,925評論 2 344

推薦閱讀更多精彩內(nèi)容