Swift 3 0 FMDB 初试
生活随笔
收集整理的這篇文章主要介紹了
Swift 3 0 FMDB 初试
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
###1、pod導入FMDB
- podfile 內容如下:
- pod install
2、FMDB的使用
import UIKit import FMDBclass 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 StringpathToDatabase = documentsDirectory.appending("/\(databaseFileName)")print(pathToDatabase)}func creatDatabase()->Bool{var created = falseif !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 = truedatabase.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()}} } 復制代碼轉載于:https://juejin.im/post/5a31ebd36fb9a0450b66667d
總結
以上是生活随笔為你收集整理的Swift 3 0 FMDB 初试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sass的高级用法
- 下一篇: 爬虫、框架scrapy