美文网首页IOSiOS学习笔记
swift之SQLite.swift的使用

swift之SQLite.swift的使用

作者: 见哥哥长高了 | 来源:发表于2019-12-28 11:49 被阅读0次
集成

集成非常简单,可以把SQLite.swift下载下来直接拖进项目中,也可以用cocoaPods来继承,为了省事我使用的cocoaPods。

source 'https://github.com/CocoaPods/Specs.git'
platform:ios,'10.0'
use_frameworks!

target 'SwiftStudy03' do

pod 'SQLite.swift', '~> 0.12.2'

xcodeproj '/Users/adiqueen/Desktop/SwiftStudyDemos/SwiftStudy04/SwiftStudy03.xcodeproj'

end
另外,为了能能够正常的使用SQLite.swift,需要在General->Frameworks,Libraries,and Embedded Content添加SystemConfigration.framework 添加SystemConfigration.framework

需要的地方直接:import SQLite 引入即可。
下面是一个简单封装的事例代码,仅供个人学习于参考。

LGJDataStore

单例类,建表连库

import Foundation
import SQLite

enum DataAccessError: Swift.Error {
    case datastoreConnectionError
    case insertError
    case deleteError
    case searchError
    case nilInData
    case nomoreData
}

class LGJDataStore {
    
    static let sharedInstance = LGJDataStore()
    let LGJDB: Connection?
    
    private init() {
        
        let dirs: [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true) as [String]
        let dir = dirs[0]
        let path = dir.appending("LGJ.sqlite")
        print("The DB Path:", path)
        
        do {
            LGJDB = try Connection.init(path)
            LGJDB?.busyTimeout = 5
            LGJDB?.busyHandler({ tries in
                if tries >= 3 {
                    return false
                }
                return true
            })
        }catch _ {
            LGJDB = nil
        }
    }
    
    func createTables() throws {
        do {
            try LGJDataHelper.createTable()
        } catch {
            throw DataAccessError.datastoreConnectionError
        }
        
    }
    
}
LGJDataHelperProtocol

协议,声明一系列增删改查的操作

import Foundation

protocol LGJDataHelperProtocol {
    
    associatedtype T
    
    static func createTable() throws -> Void
    
    static func insert(item: T) throws -> Int
    
    static func find(queryUserId: Int) throws -> [T]
    
}

//Optional implementation
extension LGJDataHelperProtocol {
    
    static func update(id: Int, value: T) throws -> T? {return nil}
    
    static func update(item: T) throws -> Bool {return false}
    
    static func delete(item: T) throws -> Bool {return false}
    
    static func findAll() throws -> [T]? {return nil}
    
    static func checkColimnExists(queryUserId: Int) throws -> Bool { return false }
    
}

LGJDataHelper

一个实现LGJDataHelperProtocol的class,完成具体的数据操作

import Foundation
import SQLite

class LGJDataHelper: LGJDataHelperProtocol {
    
    static let TABLE_NAME = "lgj_userinfo"
    
    static let userId = Expression<Int>("userId")
    static let name = Expression<String>("name")
    static let icon = Expression<UIImage>("icon")
    
    static let table = Table(TABLE_NAME)
    
    typealias T = LGJUserInfoModel
    
    static func createTable() throws {
        
        guard let DB = LGJDataStore.sharedInstance.LGJDB else {
            throw DataAccessError.datastoreConnectionError
        }
        do {
            _ = try DB.run(table.create(ifNotExists: true){t in
                t.column(userId)
                t.column(name)
                t.column(icon)
            })
        }catch _ {
            throw DataAccessError.datastoreConnectionError
        }
    }
    
    static func insert(item: T) throws -> Int {
        
        guard let DB = LGJDataStore.sharedInstance.LGJDB else {
            throw DataAccessError.datastoreConnectionError
        }
        
        let insert = table.insert(userId <- item.userId, name <- item.name, icon <- item.icon)
        do {
            let rowId = try DB.run(insert)
            guard rowId >= 0 else {
                throw DataAccessError.insertError
            }
            return Int(rowId)
        }catch _ {
            throw DataAccessError.insertError
        }
    }
    
    static func update(item: T) throws -> Bool {
        
        guard let DB = LGJDataStore.sharedInstance.LGJDB else {
            throw DataAccessError.datastoreConnectionError
        }
        
        let query = table.filter(item.userId == userId)
        
        if try DB.run(query.update(userId <- item.userId, name <- item.name, icon <- item.icon)) > 0 {
            return true
        }else{
            return false
        }
        
    }
    
    
    static func checkColimnExists(queryUserId: Int) throws -> Bool {
        
        guard let DB = LGJDataStore.sharedInstance.LGJDB else {
            throw DataAccessError.datastoreConnectionError
        }
        
        let query = table.filter(queryUserId == userId).exists

        let isExists = try DB.scalar(query)
        return isExists
        
    }
    
    static func delete(item: T) throws -> Bool {
        
        guard let DB = LGJDataStore.sharedInstance.LGJDB else {
            throw DataAccessError.datastoreConnectionError
        }
        
        let id = item.userId
        
        let query = table.filter(userId == id)
        do {
            let tmp = try DB.run(query.delete())
            
            guard tmp == 1 else {
                throw DataAccessError.deleteError
            }
        }catch _ {
            throw DataAccessError.deleteError
        }
        return true
    }
    
    static func find(queryUserId: Int) throws -> [LGJUserInfoModel] {
        
        guard let DB = LGJDataStore.sharedInstance.LGJDB else {
            throw DataAccessError.datastoreConnectionError
        }
        
        let query = table.filter(queryUserId == userId)
        let items = try DB.prepare(query)
        var retArray = [T]()
        for item in items {
            retArray.append(LGJUserInfoModel(userId: item[userId], name: item[name], icon: item[icon]))
        }
        return retArray
    }
    
    static func findAll() throws -> [LGJUserInfoModel]? {
        
        guard let DB = LGJDataStore.sharedInstance.LGJDB else {
            throw DataAccessError.datastoreConnectionError
        }
        var retArray = [T]()
        let items = try DB.prepare(table)
        for item in items {
            retArray.append(LGJUserInfoModel(userId: item[userId], name: item[name],icon: item[icon]))
        }
        return retArray
    }
    
    
}

LGJUserInfoModel

用户数据模型,简单定义了属性、初始化方法及数据存储实现。


import Foundation
import UIKit
import SQLite


// user info
struct LGJUserInfoModel {
    
    var userId: Int = 0
    var name: String = ""
    var icon: UIImage = UIImage.init(named: "default")!
    
    init() {}
    
    init(userId: Int, name: String, icon: UIImage) {
        self.userId = userId
        self.name = name
        self.icon = icon
    }
}


extension NSData: Value {

    //SQL Type
    public static var declaredDatatype: String {
        return Blob.declaredDatatype
    }

    //Decode
    public static func fromDatatypeValue(_ datatypeValue: Blob) -> NSData {
        return NSData(bytes: datatypeValue.bytes, length: datatypeValue.bytes.count)
    }
    
    //Encode
    public var datatypeValue: Blob {
        return Blob(bytes: self.bytes, length: self.length)
    }

}


extension UIImage: Value {
    
    public static var declaredDatatype: String{
        return Blob.declaredDatatype
    }

    public static func fromDatatypeValue(_ blobValue: Blob) -> UIImage {
        return UIImage(data: Data.fromDatatypeValue(blobValue))!
    }
    
    public var datatypeValue: Blob {
        return self.pngData()!.datatypeValue
    }
    
}

具体应用起来就简单的多了

//MARK
extension ViewController {
    
    func creatDB()  {
        do {
            try LGJDataStore.sharedInstance.createTables()
        }catch _ {
            print("create DB error")
        }
    }
    
    func insertUserModel()  {
        
        let userModel = LGJUserInfoModel(userId: 100, name: "liugaojian", icon: UIImage.init(named: "default")!)
        do {
           let torId = try LGJDataHelper.insert(item: userModel)
            print(torId)
        } catch _ {
            print("insert userModel error")
        }
        
    }
    
    func checkUserModel() {
        do {
            let exists =  try LGJDataHelper.checkColimnExists(queryUserId: 100)
            print(exists)
        } catch _ {
            print("check userModel error")
        }
    }
    
    func updateUserModel()  {
        
        let userModel = LGJUserInfoModel(userId: 100, name: "guhongjuan", icon: UIImage.init(named: "local")!)
        do {
            let isSuccess =  try LGJDataHelper.update(item: userModel)
            print(isSuccess)
        } catch _ {
                print("update userModel error")
        }
    }
    
    func getUserModel()  {
        do {
            let items = try LGJDataHelper.find(queryUserId: 100)
            
            if let item = items.first {
                print(item.userId, item.name, item.icon)
            }
            
        } catch _ {
            print("get userModel error")
        }
    }
    
    func getAllUserModel()  {
        
        do {
            let items =  try LGJDataHelper.findAll()!
            for item: LGJUserInfoModel in items {
                print(item.userId, item.name, item.icon)
            }
        } catch _ {
            print("find userModel error")
        }
    }
}

触发以下方法

        creatDB()
        
        insertUserModel()
        
        checkUserModel()
        
        updateUserModel()
        
        getUserModel()
        
        getAllUserModel()

因为我们有些功能实现了简单的打印操作,下面是打印结果:


打印

相关文章

网友评论

    本文标题:swift之SQLite.swift的使用

    本文链接:https://www.haomeiwen.com/subject/asqsoctx.html