iOSSwift

iOS 开发 swift项目使用FMDB

2017-03-18  本文已影响126人  MrZhaoCn

FMDB作为iOS开发中sqlite数据库的第三方库,避免了直接使用sqlite的繁琐,本文将讲解在swift工程中如何使用FMDB。
第一步:首先将FMDB导入工程中,并在桥接文件中添加#import "FMDB.h"。
第二步:定义一个类继承自NSObject。

import UIKit
class YRSchedualTool: NSObject {
    static let shared: YRSchedualTool = YRSchedualTool() //单例
    let databaseFileName = "schedual.sqlite" //数据库名
    var pathToDatabase: String!  //数据库路径
    var database: FMDatabase!  //数据库
    override init() {
        super.init()
        let documentsDirectory = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString) as String
        pathToDatabase = documentsDirectory.appending("/\(databaseFileName)")
        print(pathToDatabase)
    }
    
    func createDatabase() -> Bool {
        var created = false
        if !FileManager.default.fileExists(atPath: pathToDatabase) {
            database = FMDatabase(path: pathToDatabase!) //创建数据库
            if database != nil {
                // Open the database.
                if database.open() { //打开
                    let createSchedualTableQuery = "create table if not exists t_schedual (id integer primary key autoincrement,schedual_id integer not null,endTime integer not null);"
                    database.executeUpdate(createSchedualTableQuery, withArgumentsIn: nil) //建表
                    created = true
                    database.close()
                }
                else {
                    print("Could not open the database.")
                }
            }
        }
        return created
    }
    
    func openDatabase() -> Bool {
        if database == nil {
            if FileManager.default.fileExists(atPath: pathToDatabase) {
                database = FMDatabase(path: pathToDatabase)
            }
        }
        if database != nil {
            if database.open() {
                return true
            }
        }
        return false
    }
    
    
//数据库插入操作   
 func insertScedualData(schedualId:Int32,endTime:Int32) {
        if openDatabase() {
            let sqlString = "insert into t_schedual (schedual_id, endTime) values ('\(schedualId)', '\(endTime)')"
            if !database.executeStatements(sqlString) {
                    print("Failed to insert initial data into the database.")
                    print(database.lastError(), database.lastErrorMessage())
            }
            database.close()
        }
    }
    
    //数据库查询,YRSchedualModel是我项目中的一个模型
    func loadSchedualDatas() -> [YRSchedualModel]! {
        var schedualDatas = [YRSchedualModel]()
        if openDatabase() {
            let query = "select * from t_schedual order by schedual_id asc;"
            let results = database.executeQuery(query, withArgumentsIn: nil)
            while (results?.next())! {
                    let schedual = YRSchedualModel()
                    let schedualId = results?.object(forColumnName: "schedual_id")
                    let endTime = results?.object(forColumnName: "endTime")
                    schedual.id = (schedualId as? Int32)!
                    schedual.end_time = (endTime as? Int32)!
                    schedualDatas.append(schedual)
            }
            database.close()
        }
        return schedualDatas
    }
    func loadSchedual(schedual_id:Int32) -> YRSchedualModel? {
        if openDatabase() {
//查询时问号作为占位符占位,在database.executeQuery中将占位的参数带上。
            let query = "select * from t_schedual where schedual_id = ?"
            let results = database.executeQuery(query, withArgumentsIn: [schedual_id])
            var schedualM:YRSchedualModel?
            while (results?.next())! {
                schedualM = YRSchedualModel()
                let schedualId = results?.object(forColumnName: "schedual_id")
                let endTime = results?.object(forColumnName: "endTime")
                schedualM?.id = (schedualId as? Int32)!
                schedualM?.end_time = (endTime as? Int32)!
            }
            database.close()
            return schedualM
        }
        return nil
    }
    //删除
    func deleteSchedual(endTime: Int32) -> Bool {
        var deleted = false
        if openDatabase() {
            let query = "delete from t_schedual where endTime < ?"
            database.executeUpdate(query, withArgumentsIn: [endTime])
            deleted = true
            database.close()
        }
        return deleted
    }
}

第三步使用:

//数据库只会被创建一次,如果已经创建则不会再创建
 _ = YRSchedualTool.shared.createDatabase()
//读取数据
let synchronizedScheduals:[YRSchedualModel] = YRSchedualTool.shared.loadSchedualDatas()
 //插入数据到数据库
 YRSchedualTool.shared.insertScedualData(schedualId: item.id, endTime: item.end_time)
//删除指定条件的数据
_ = YRSchedualTool.shared.deleteSchedual(endTime: endTime)

以上就是swift项目下FMDB的基本使用,欢迎大家批评指正!!!

上一篇下一篇

猜你喜欢

热点阅读