FMDB在OC中使用較多, 來到swift的世界,依然不想放棄他,下面就來看一下如何在swift中使用;
說明: 因為文章中的所有代碼塊都是完整的功能,可直接使用,所以導(dǎo)致文章篇幅過長, 其實內(nèi)容不是很多,可直接下載demo:LQQZYY/FMDB-Swift, 線程安全的操作數(shù)據(jù)庫:FMDB-Swift-Queue,需要修改數(shù)據(jù)模型及表的字段為自己的需求才能使用, 格式可保持不變.
1. 準(zhǔn)備
首先,從github-FMDB下載其源文件,解壓后將src文件夾下的fmdb添加到項目中,然后,將extra文件夾下的Swift extensions也添加進(jìn)來;
然后,在項目Build Phases的Link Binary With Libraries添加系統(tǒng)依賴庫 libsqlite3.tbd
最后,添加橋接文件,如果你不會添加,請參考[Swift]創(chuàng)建Objective-C混編橋接文件
在橋接文件中導(dǎo)入頭文件:
#import "FMDB.h"
編譯一下,這時你會發(fā)現(xiàn)Swift extensions文件夾下的文件會報錯:
應(yīng)該是還沒有升級到swift3.0,根據(jù)提示,自動矯正; 系統(tǒng)提示的矯正完后,還會有兩個下面這樣的錯誤:
我的做法是將函數(shù)的返回值類型NSData! 改為 Data!,即:
另一個錯誤做一樣的更改.
再編譯,應(yīng)該就沒有錯誤了,好了,準(zhǔn)備完畢!!!
2. 使用
使用和OC很相似,只是寫法上的不同, 需要注意的是,怎么創(chuàng)建單例的FMDatabase實例對象, 我這里使用的是懶加載的模式:
private static var database: FMDatabase = {
if LZSqlite.path == nil || (LZSqlite.path?.characters.count)! <= 0 {
LZSqlite.createSqliteWithName("myDB.db")
}
let db = FMDatabase.init(path: LZSqlite.path!)
return db!
}()
這里的path是數(shù)據(jù)庫的保存路徑
private static var path: String!
我沒有把這個屬性直接讓外部訪問,是因為,我單獨寫了一個方法,來創(chuàng)建數(shù)據(jù)庫文件:
static func createSqliteWithName(_ name: String) {
var fileName = ""
let strArr = name.components(separatedBy: ".")
if strArr.last == "sqlite" || strArr.last == "db" {
fileName = name
} else {
fileName = name + ".db"
}
let path = NSHomeDirectory() + "/Documents/" + fileName
LZSqlite.path = path
let fm = FileManager.default
if fm.fileExists(atPath: path) == false {
fm.createFile(atPath: path, contents: nil, attributes: nil)
}
print("dataBase path: \(LZSqlite.path)")
}
數(shù)據(jù)庫文件創(chuàng)建好了,下面就是建表了,因為每個項目中表的格式都不一樣,需求多樣,這里只是示例創(chuàng)建方法,真正使用的時候根據(jù)自己的額需求來設(shè)計即可:
static func createTable(_ name: String) {
if LZSqlite.database.open() == false {
LZSqlite.database.close()
return
}
LZSqlite.database.setShouldCacheStatements(true)
if LZSqlite.database.tableExists(name) == false {
let create = "CREATE TABLE IF NOT EXISTS '\(name)' (ID TEXT UNIQUE NOT NULL, groupName TEXT, groupID TEXT NOT NULL, nickName TEXT, userName TEXT, psw TEXT, urlString TEXT, email TEXT, dsc TEXT)"
do {
try LZSqlite.database.executeUpdate(sql: create)
} catch {
print("Error: table \(name) create fail")
}
}
LZSqlite.database.close()
}
這里寫SQL語句的時候需要注意, 占位符 ?在這里好像不能使用,至少我使用的時候是不行的, 因為swift中插入字符串真的是十分的方便, 我就直接使用這種簡單而又清楚的方式來拼接SQL語句;
表的刪除,可使用這個方法:
static func deleteTable(_ name: String) {
if LZSqlite.database.open() == false {
LZSqlite.database.close()
return
}
LZSqlite.database.setShouldCacheStatements(true)
if LZSqlite.database.tableExists(name) {
let drop = "DROP TABLE '\(name)'"
do {
try LZSqlite.database.executeUpdate(sql: drop)
} catch {
print("Error: table \(name) drop failed")
}
}
下面這個方法,是為已有的表添加一列元素:
static func alterElement(_ element: String, toTable table: String) {
if LZSqlite.database.open() == false {
LZSqlite.database.close()
return
}
LZSqlite.database.setShouldCacheStatements(true)
if LZSqlite.database.tableExists(table) {
do {
try LZSqlite.database.executeUpdate(sql: "ALTER TABLE '\(table)' ADD '\(element)' TEXT")
} catch {
print("Error: alter new element: \"\(element)\" to table: \"\(table)\" failed")
}
}
LZSqlite.database.close()
}
表建好了,接下來就是增 / 刪 / 改 /** 查** 等操作了:
2.1 增
直接上代碼了:
static func insert(model: LZDataModel, toTable table: String) {
if LZSqlite.database.open() == false {
LZSqlite.database.close()
return
}
LZSqlite.database.setShouldCacheStatements(true)
if LZSqlite.database.tableExists(table) {
let insert = "INSERT INTO '\(table)' (ID, groupName, nickName, userName, psw, urlString, email, dsc, groupID) VALUES ('\(model.identifier)', '\(model.groupName)', '\(model.nickName)', '\(model.userName)', '\(model.password)', '\(model.urlString)', '\(model.email)', '\(model.dsc)', '\(model.groupID)')"
do {
try LZSqlite.database.executeUpdate(sql: insert)
} catch {
print("Error: insert new model into table:\(table) failed")
}
}
LZSqlite.database.close()
}
這是往表內(nèi)添加一條數(shù)據(jù),model是自定義的;
**需要注意的是: **如果model的屬性是可選型, 那么存入數(shù)據(jù)庫的也是可選類型, 這樣在執(zhí)行查詢/修改等操作的時候, 稍不注意就會出現(xiàn)問題, 例如: 如果我們使用ID來更新某條數(shù)據(jù),你傳進(jìn)來的ID參數(shù)多數(shù)情況下不是可選型,而是真真正正的字符串, 而你存進(jìn)數(shù)據(jù)庫的是可選型這樣是找不到這條數(shù)據(jù)的, 所以在存入數(shù)據(jù)庫前, 要對屬性的可選型進(jìn)行解包;
如上圖所示:
下面十條數(shù)據(jù),是我沒有對可選型屬性進(jìn)行解包,直接存儲的;
上面的數(shù)據(jù),是我解包后存儲的;
其中的區(qū)別很明顯, 為了使用方便, 個人建議解包后再存儲, 雖然解包的過程會有些繁瑣.
下面這個方法, 是我加入了對可選型進(jìn)行解包的操作:
static func insertOptional(model: LZDataModel, toTable table: String) {
if LZSqlite.database.open() == false {
LZSqlite.database.close()
return
}
LZSqlite.database.setShouldCacheStatements(true)
if LZSqlite.database.tableExists(table) {
var identifier: String = ""
var groupName: String = ""
var nickName: String = ""
var userName: String = ""
var password: String = ""
var urlString: String = ""
var email: String = ""
var dsc: String = ""
var groupID: String = ""
if let tmp = model.identifier {
identifier = tmp
}
if let tmp = model.groupName {
groupName = tmp
}
if let tmp = model.nickName {
nickName = tmp
}
if let tmp = model.userName {
userName = tmp
}
if let tmp = model.password {
password = tmp
}
if let tmp = model.urlString {
urlString = tmp
}
if let tmp = model.email {
email = tmp
}
if let tmp = model.dsc {
dsc = tmp
}
if let tmp = model.groupID {
groupID = tmp
}
let insert = "INSERT INTO '\(table)' (ID, groupName, nickName, userName, psw, urlString, email, dsc, groupID) VALUES ('\(identifier)', '\(groupName)', '\(nickName)', '\(userName)', '\(password)', '\(urlString)', '\(email)', '\(dsc)', '\(groupID)')"
do {
try LZSqlite.database.executeUpdate(sql: insert)
} catch {
print("Error: insert new model into table:\(table) failed")
}
}
LZSqlite.database.close()
}
因為數(shù)據(jù)模型一般都是我們定義好的,不會有變化,所以我們知道哪些屬性是可選型,哪些不是,所以我們只需要判斷其是否有值即可, 直接這樣寫是沒有問題的;
2.2 刪
刪除的操作就比較簡單了:
static func delete(model: LZDataModel, fromTable table: String) {
if LZSqlite.database.open() == false {
LZSqlite.database.close()
return
}
LZSqlite.database.setShouldCacheStatements(true)
if LZSqlite.database.tableExists(table) {
do {
try LZSqlite.database.executeUpdate(sql: "DELETE FROM '\(table)' WHERE ID = '\(model.identifier)'")
} catch {
print("Error: delete model from table: \"\(table)\" failed")
}
}
LZSqlite.database.close()
}
2.3 改
修改的操作,情況相對較多,如果你能確定修改的內(nèi)容, 可以只修改需要修改的,如果不能確定, 就將整條數(shù)據(jù)更新一下, 這里,我是更新的整條數(shù)據(jù), 當(dāng)然,如果你能確定某個屬性一旦存儲就不會改變,例如ID, 可以不用更改:
static func update(model: LZDataModel, inTable table: String) {
if LZSqlite.database.open() == false {
LZSqlite.database.close()
return
}
LZSqlite.database.setShouldCacheStatements(true)
if LZSqlite.database.tableExists(table) {
let update = "UPDATE '\(table)' SET userName = '\(model.userName)', psw = '\(model.password)', nickName = '\(model.userName)', groupName = '\(model.groupName)', dsc = '\(model.dsc)', urlString = '\(model.urlString)', groupID = '\(model.groupID)', email = '\(model.email)' WHERE ID = '\(model.identifier)'"
do {
try LZSqlite.database.executeUpdate(sql: update)
} catch {
print("Error: update table: \"\(table)\" failed")
}
}
LZSqlite.database.close()
}
2.4 查
查詢的情況也挺多: 查詢?nèi)繑?shù)據(jù), 查詢某條數(shù)據(jù), 查詢某個區(qū)間的數(shù)據(jù), 查詢數(shù)據(jù)庫中數(shù)據(jù)的數(shù)目等;
這里直接給出代碼:
查詢所有數(shù)據(jù):
static func selectAllFromTable(_ table: String) -> [LZDataModel]? {
if LZSqlite.database.open() == false {
LZSqlite.database.close()
return nil
}
LZSqlite.database.setShouldCacheStatements(true)
if LZSqlite.database.tableExists(table) {
let select = "SELECT * FROM '\(table)'"
do {
let fs = try LZSqlite.database.executeQuery(sql: select)
var tempModels = [LZDataModel]()
while fs.next() {
let model = LZDataModel()
model.identifier = fs.string(forColumn: "ID")
model.nickName = fs.string(forColumn: "nickName")
model.userName = fs.string(forColumn: "userName")
model.password = fs.string(forColumn: "psw")
model.urlString = fs.string(forColumn: "urlString")
model.dsc = fs.string(forColumn: "dsc")
model.groupName = fs.string(forColumn: "groupName")
model.groupID = fs.string(forColumn: "groupID")
model.email = fs.string(forColumn: "email")
tempModels.append(model)
}
fs.close()
LZSqlite.database.close()
return tempModels
} catch {
print("Error: select models from table: \"\(table)\" failed")
}
}
LZSqlite.database.close()
return nil
}
查詢某條數(shù)據(jù):
static func selectModelWithID(_ identifier: String, fromTable table: String) -> LZDataModel? {
if LZSqlite.database.open() == false {
LZSqlite.database.close()
return nil
}
LZSqlite.database.setShouldCacheStatements(true)
if LZSqlite.database.tableExists(table) {
do {
let fs = try LZSqlite.database.executeQuery(sql: "SELECT * FROM '\(table)' WHERE ID = '\(identifier)'")
if fs.next() {
let model = LZDataModel()
model.identifier = fs.string(forColumn: "ID")
model.nickName = fs.string(forColumn: "nickName")
model.userName = fs.string(forColumn: "userName")
model.password = fs.string(forColumn: "psw")
model.urlString = fs.string(forColumn: "urlString")
model.dsc = fs.string(forColumn: "dsc")
model.groupName = fs.string(forColumn: "groupName")
model.groupID = fs.string(forColumn: "groupID")
model.email = fs.string(forColumn: "email")
fs.close()
LZSqlite.database.close()
return model
}
} catch {
print("Error: select model from table: \"\(table)\" with id: \"\(identifier)\" failed")
}
}
LZSqlite.database.close()
return nil
}
查詢某個區(qū)間的數(shù)據(jù):
static func selectPart(_ range: CountableClosedRange<Int>, fromTable table: String) -> [LZDataModel]? {
if LZSqlite.database.open() == false {
LZSqlite.database.close()
return nil
}
LZSqlite.database.setShouldCacheStatements(true)
if LZSqlite.database.tableExists(table) {
let select = "SELECT * FROM '\(table)' LIMIT \(range.lowerBound), \(range.upperBound - range.lowerBound)"
do {
let fs = try LZSqlite.database.executeQuery(sql: select)
var tempModels = [LZDataModel]()
while fs.next() {
let model = LZDataModel()
model.identifier = fs.string(forColumn: "ID")
model.nickName = fs.string(forColumn: "nickName")
model.userName = fs.string(forColumn: "userName")
model.password = fs.string(forColumn: "psw")
model.urlString = fs.string(forColumn: "urlString")
model.dsc = fs.string(forColumn: "dsc")
model.groupName = fs.string(forColumn: "groupName")
model.groupID = fs.string(forColumn: "groupID")
model.email = fs.string(forColumn: "email")
tempModels.append(model)
}
fs.close()
LZSqlite.database.close()
return tempModels
} catch {
print("Error: select models from table: \"\(table)\" failed")
}
}
LZSqlite.database.close()
return nil
}
這里函數(shù)參數(shù)的區(qū)間類型可查看我的另一篇文章:[Swift]使用區(qū)間作為函數(shù)的參數(shù)
查詢已存儲數(shù)據(jù)的數(shù)目:
static func countOf(table: String) -> Int {
if LZSqlite.database.open() == false {
LZSqlite.database.close()
return 0
}
LZSqlite.database.setShouldCacheStatements(true)
if LZSqlite.database.tableExists(table) {
do {
let fs = try LZSqlite.database.executeQuery(sql: "SELECT count(*) FROM '\(table)'")
var count = 0
if fs.next() {
count = Int(fs.int(forColumn: "count(*)"))
}
fs.close()
LZSqlite.database.close()
return count
} catch {
print("Error: select the element count of \(table) failed")
}
}
LZSqlite.database.close()
return 0
}
3. 測試
以上方法都是完整的,可以直接使用, 這里給出部分使用方法:
3.1 創(chuàng)建sqlite文件
LZSqlite.createSqliteWithName("sqliteName")
3.2 刪除sqlite文件
LZSqlite.clearSqlite()
3.3 創(chuàng)建表
LZSqlite.createTable("table")
3.4 刪除表
LZSqlite.deleteTable("table")
3.5 向表內(nèi)添加一列
LZSqlite.alterElement("ddddd", toTable: "table")
3.6 插入數(shù)據(jù)
for _ in 0...10 {
let model = LZDataModel()
model.identifier = "id\(arc4random()%10000 + 100)"
model.userName = "name\(arc4random()%100 + 10)"
model.groupID = "groupid\(arc4random()%1000 + 100)"
model.groupName = "group\(arc4random()%100 + 10)"
model.password = "password\(arc4random()%1000 + 100)"
// 對可選項進(jìn)行解包
// LZSqlite.insertOptional(model: model, toTable: "table")
// 不對可選項進(jìn)行解包
LZSqlite.insert(model: model, toTable: "table")
}
3.7 刪除數(shù)據(jù)
LZSqlite.delete(model: model, fromTable: "table")
3.8 更新數(shù)據(jù)
LZSqlite.update(model: model, inTable: "table")
3.9 查詢數(shù)據(jù)庫中數(shù)據(jù)數(shù)目
LZSqlite.countOf(table: "table")
3.10 查詢所有數(shù)據(jù)
LZSqlite.selectAllFromTable("table")
3.11 查詢某條數(shù)據(jù)
LZSqlite.selectModelWithID("id124" , fromTable: "table")
3.12 查詢某個區(qū)間的數(shù)據(jù)
LZSqlite.selectPart(10...20, fromTable: "table")
是不是很方便?
本工具的github地址:** LQQZYY/FMDB-Swift**
線程安全的操作數(shù)據(jù)庫:FMDB-Swift-Queue
如果對你有幫助還請star或fork來鼓勵一下,謝謝!
(完)
Github | LQQZYY |
CSDN博客 | 流火緋瞳 |
新浪微博 | 杯水_滄海 |
302934443 |