Swift 3.0 FMDB 初试

1、pod导入FMDB

  • podfile 内容如下:
# Uncomment the next line to define a global platform for your project
platform :ios, ‘8.0’

target 'FMDBTest' do

use_frameworks!

pod 'FMDB’


end

  • pod install

2、FMDB的使用

import UIKit
import FMDB

class MDFMDB: NSObject {
   static let shared: MDFMDB = MDFMDB() //单例
    let databaseFileName = "test.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  creatDatabase()->Bool{
        var created = false
        if !FileManager.default.fileExists(atPath: pathToDatabase){
            database = FMDatabase(path: pathToDatabase)
            if database != nil{
                if database.open() {
                   //如果user表不存在,创建user表
                    let createSchedualTableQuery = "create table if not exists user (id integer primary key autoincrement,name string not null,gender string not null,age string not null);"
                    database.executeUpdate(createSchedualTableQuery, withArgumentsIn: []) //建表
                    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(name:String,gender:String,age:String) {
        if openDatabase() {
            let sqlString = "insert into user (name, gender, age) values ('\(name)', '\(gender)', '\(age)')"
            if !database.executeStatements(sqlString) {
                print("Failed to insert initial data into the database.")
                print(database.lastError(), database.lastErrorMessage())
            }
            database.close()
        }
    }
    
    
    //数据库读取操作
    func loadTestDatas(){
        if openDatabase() {
            let query = "select * from user order by name asc;"
            let results = database.executeQuery(query, withArgumentsIn: [])
            while (results?.next())! {
                let id = results?.object(forColumn: "id")
                print(id!)
                let name = results?.object(forColumn: "name")
                print(name!)
                let gender = results?.object(forColumn: "gender")
                print(gender!)
                let age = results?.object(forColumn: "age")
                print(age!)
            }
            database.close()
        }
    }
    //数据库读取(具体)
    func loadTest(id : NSInteger){
        if openDatabase() {
            //查询时问号作为占位符占位,在database.executeQuery中将占位的参数带上。
            let query = "select * from user where id = ?"
            let results = database.executeQuery(query, withArgumentsIn: [id])
            while (results?.next())! {
                let id = results?.object(forColumn: "id")
                print(id!)
                let name = results?.object(forColumn: "name")
                print(name!)
                let gender = results?.object(forColumn: "gender")
                print(gender!)
                let age = results?.object(forColumn: "age")
                print(age!)
            }
            database.close()
        }
    } 
}

你可能感兴趣的:(Swift 3.0 FMDB 初试)