swift中使用FMDB

作者: 皮乐皮儿 | 来源:发表于2017-01-11 14:45 被阅读105次

    iOS常用的第三方数据管理库就是FMDB了,这个库比较轻量级,而且使用起来非常方便,在学习swift的过程中,试过用SQLite3,然鹅过于繁琐和复杂,最终还是采用了桥接方式使用了OC库FMDB

    1.首先导入FMDB库,这个就不多说了,有两种方法:1.用CocoaPods管理 2.手动下载导入

    2.创建数据管理的类

        static let shared:DataBaseTool = DataBaseTool()
        
        var pathToDataBase:String!
        
        var dataBase:FMDatabase!
        
        override init() {
            super.init()
            let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
            pathToDataBase = documentDirectory.appending("dataBase.sqlite")
            createDataBase()
        }
    }
    

    3. 创建表,这里以创建用户表为例:

     func createDataBase() {
            dataBase = FMDatabase(path: pathToDataBase)
    
                    if dataBase.open() {
                        let createUserMessageSQL = "create table if not exists UserMessageTab(userID text primary key,userName text,nickName text,avatarUrl text,userEmail text,userType int,sex int,createdAt text,updatedAt text,deviceId text,birthDay int,birthMonth int,birthYear int,emailBindStatus int,newsAuthToken text,thirdDetailList blob,thirdStyleList blob);"
                        do {
                            try dataBase.executeUpdate(createUserMessageSQL, values: nil)
                        } catch  {
                            print("用户信息表创建失败")
                        }
    }
    

    4. 插入数据

        //增加
        func saveUserMessageModel(userMessageModel:UserMessageModel) {
            
            if dataBase.open() {
                let model = UserMessageModel()
                var rs:FMResultSet!
                
                
                do {
                   rs = try dataBase.executeQuery("SELECT * FROM UserMessageTab", values: nil)
                
                    while rs.next() {
                        model.ID = rs.string(forColumn: "userID")
                    }
                    if model.ID != nil {
                        deleteUserMessage()
                    }
                    let thirdDetailData = NSKeyedArchiver.archivedData(withRootObject: userMessageModel.thirdDetailList)
                    let thirdStyleData = NSKeyedArchiver.archivedData(withRootObject: userMessageModel.thirdStyleList)
                    let parameters = [userMessageModel.ID!,userMessageModel.userName,userMessageModel.nickName,userMessageModel.avatarUrl,userMessageModel.userEmail,userMessageModel.userType,userMessageModel.sex,userMessageModel.createdAt,userMessageModel.updatedAt,userMessageModel.deviceId,userMessageModel.birthDay,userMessageModel.birthMonth,userMessageModel.birthYear,userMessageModel.emailBindStatus,userMessageModel.newsAuthToken,thirdDetailData,thirdStyleData] as [Any]
                    
                    let success:Bool = dataBase.executeUpdate("insert into UserMessageTab (userID, userName, nickName, avatarUrl, userEmail, userType, sex, createdAt, updatedAt, deviceId, birthDay, birthMonth, birthYear, emailBindStatus, newsAuthToken, thirdDetailList, thirdStyleList) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", withArgumentsIn: parameters)
    //
                    if success {
                    print("插入数据成功")
                    }else {
                    print("插入数据失败")
                    }
                    
                    dataBase.close()
                    
                } catch  {
                    
                }
                
            }
        }
    
    

    5.删除数据:

        //删除
        func deleteUserMessage() {
            if dataBase.open() {
                if dataBase.executeUpdate("DELETE FROM UserMessageTab", withArgumentsIn: nil) {
                   print("删除数据成功")
                }else {
                   print("删除数据失败")
                }
                dataBase.close()
            }
        }
    
    

    6.查询数据:

        func selectUserMessage() ->UserMessageModel {
            let model = UserMessageModel()
    
            if dataBase.open() {
                var rs:FMResultSet!
                
                
                do {
                    rs = try dataBase.executeQuery("SELECT * FROM UserMessageTab", values: nil)
                    
                    while rs.next() {
                        model.ID = rs.string(forColumn: "userID")
                        model.userName = rs.string(forColumn: "userName")
                        model.nickName = rs.string(forColumn: "nickName")
                        model.avatarUrl = rs.string(forColumn: "avatarUrl")
                        model.userEmail = rs.string(forColumn: "userEmail")
                        model.newsAuthToken = rs.string(forColumn: "newsAuthToken")
                        model.userType = Int(rs.int(forColumn: "userType"))
                        model.sex = Int(rs.int(forColumn: "sex"))
                        model.createdAt = rs.string(forColumn: "createdAt")
                        model.updatedAt = rs.string(forColumn: "updatedAt")
                        model.deviceId = rs.string(forColumn: "deviceId")
                        model.birthDay = Int(rs.int(forColumn: "birthDay"))
                        model.birthMonth = Int(rs.int(forColumn: "birthMonth"))
                        model.birthYear = Int(rs.int(forColumn: "birthYear"))
                        model.emailBindStatus = Int(rs.int(forColumn: "emailBindStatus"))
                       let thirdStyleList = rs.data(forColumn: "thirdStyleList")
                       let thirdDetailList = rs.data(forColumn: "thirdDetailList")
                    
                       if thirdStyleList != nil {
                        model.thirdStyleList = NSKeyedUnarchiver.unarchiveObject(with: rs.data(forColumn: "thirdStyleList")) as! [Any]
                       }
                       if thirdDetailList != nil {
                        model.thirdDetailList = NSKeyedUnarchiver.unarchiveObject(with: rs.data(forColumn: "thirdDetailList")) as! [Any]
                      }
                }
                    
                    dataBase.close()
                    
                } catch  {
                    
                }
    
            }
            return model
        }
    

    7. 更新数据(这里换了个表):

        func updateConfigModel(configModel:ConfigModel) {
            let parameters = [configModel.adShowTime,configModel.adUrl,configModel.startLogo,configModel.iosShareText,configModel.adLogo,configModel.adEnable,configModel.IOS_WEAKUP_TIMES,configModel.SEARCH_WAP_URL] as [Any]
            
            let success:Bool = dataBase.executeUpdate("update ConfigTab set adShowTime=(?),adUrl=(?),startLogo=(?),iosShareText=(?),adLogo=(?),adEnabled=(?),IOS_WEAKUP_TIMES=(?),SEARCH_WAP_URL=(?);", withArgumentsIn: parameters)
            if success {
                print("更新配置数据成功")
            }else {
                print("更新配置数据失败")
            }
    
        }
    
    

    增删改查大致这样就可以实现了,如果有比较好的swift风格的库或者处理数据的方法,欢迎大家一起学习沟通

    相关文章

      网友评论

        本文标题:swift中使用FMDB

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