Swift 3 0 FMDB 初試

z小志發表於2018-01-23

###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()
        }
    } 
}
複製程式碼

相關文章