数据缓存和FMDB是很多程序需要做的事,但是swift又有一些坑,希望这篇文章能对大家有用,除了FMDB数据库的操作,还有swift单例的写法,if let在项目中实战用法,仅供参考:
直接上代码
// Copyright © 2016年 liwei. All rights reserved.
// 未登录状态添加到购物车的数据
import UIKit
class ShopCar_SqliteTools: NSObject {
// 单例的概念:
// 1. 内存中有一个唯一的实例
// 2. 提供唯一的全局访问入口
// let 是定义常量,而且在 swift 中,let 是线程安全的
private static let shareShopCar_SqliteTools = ShopCar_SqliteTools()
/// 定义一个类变量,提供全局的访问入口,类变量不能存储数值,但是可以返回数值
class var sharedManager: ShopCar_SqliteTools {
return shareShopCar_SqliteTools
}
/// 获取FMDatabase
private func getDb()->FMDatabase{
let filemgr = NSFileManager.defaultManager()
let databasePath = "/ShopCar_Sqlite.db".documentPath()
if !filemgr.fileExistsAtPath(databasePath) {
let db = FMDatabase(path: databasePath)
if db == nil {
print("Error: \(db.lastErrorMessage())")
}
if db.open() {
let sql_stmt = "CREATE TABLE IF NOT EXISTS ShopCar_Sqlite ( \n" +
"imgurl TEXT NOT NULL DEFAULT '', \n" +
"describe TEXT NOT NULL DEFAULT '', \n" +
"ID INTEGER NOT NULL DEFAULT 0, \n" +
"number INTEGER NOT NULL DEFAULT 0, \n" +
"price TEXT NOT NULL DEFAULT '0', \n" +
"shop_id TEXT NOT NULL DEFAULT '0', \n" +
"shop_name TEXT NOT NULL DEFAULT '0', \n" +
"sku_id INTEGER NOT NULL DEFAULT 0, \n" +
"item INTEGER NOT NULL DEFAULT 0, \n" +
"sku_dic BLOB, \n" +
"keyID INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT \n" +
");"
if !db.executeStatements(sql_stmt) {
print("Error: \(db.lastErrorMessage())")
}
db.close()
} else {
print("Error: \(db.lastErrorMessage())")
}
}
let feedlogDb = FMDatabase(path: databasePath)
return feedlogDb
}
///插入数据
func insert(model:ShoppingCartModel){
//插入数据之前要查看数据库是否存在该id
let tempModel = self.selectModel(model)
if tempModel != nil {//有相同的id则更新数据
tempModel?.number = model.number! + (tempModel?.number)!
self.update(tempModel!, success: {
})
}else{
let sql="INSERT INTO ShopCar_Sqlite (imgurl,describe,ID,number,price,shop_id,shop_name,sku_id,sku_dic,item) "+"VALUES (?,?,?,?,?,?,?,?,?,?)"
let db = self.getDb()
db.open()
let sku_dic = try? NSJSONSerialization.dataWithJSONObject(model.sku_dic!, options: NSJSONWritingOptions.PrettyPrinted)
if let imgurl = model.attributeModel?.image, let describe = model.attributeModel?.name,let ID = model.skuModel?.ID,let number = model.number,let price = model.skuModel?.price,let shop_id = model.shop_id,let shop_name = model.shop_name,let sku_id = model.sku_id,let sku_dic = sku_dic,let item = model.item{
db.executeUpdate(sql, withArgumentsInArray: [imgurl,describe,ID,number,price,shop_id,shop_name,sku_id,sku_dic,item])
}
db.close()
}
}
///更新选购数量
func update(model:ShoppingCartModel,success:(()->())){
let sql = "UPDATE ShopCar_Sqlite SET number=? WHERE ID=?"
let db = self.getDb()
db.open()
db.executeUpdate(sql, withArgumentsInArray: [model.number!,model.ID!])
db.close()
success()
}
///更新model的多个属性
func updateModel(model:ShoppingCartModel){
let sql = "UPDATE ShopCar_Sqlite SET number=?,sku_dic=?,ID=? WHERE ID=?"
let db = self.getDb()
db.open()
let sku_dic = try? NSJSONSerialization.dataWithJSONObject(model.sku_dic!, options: NSJSONWritingOptions.PrettyPrinted)
if let sku_dic = sku_dic,let sku_id = model.sku_id{
db.executeUpdate(sql, withArgumentsInArray: [model.number!,sku_dic,sku_id,model.ID!])
}
db.close()
}
///删除数据一条数据
func remove(model:ShoppingCartModel){
let sql = "DELETE FROM ShopCar_Sqlite WHERE ID = ?"
let db = self.getDb()
db.open()
db.executeUpdate(sql, withArgumentsInArray: [model.ID!])
db.close()
}
///查找一条数据
func selectModel(model:ShoppingCartModel)->ShoppingCartModel? {
let sql = "SELECT * FROM ShopCar_Sqlite WHERE ID = ?"
let db = self.getDb()
db.open()
let tempModel:ShoppingCartModel
if let tempID = model.skuModel?.ID {
let rs = db.executeQuery(sql, withArgumentsInArray: [tempID])
tempModel = ShoppingCartModel()
while rs.next() {
tempModel.imgurl = rs.stringForColumn("imgurl")
tempModel.describe = rs.stringForColumn("describe")
tempModel.ID = Int(rs.intForColumn("ID"))
tempModel.number = Int(rs.intForColumn("number"))
tempModel.price = (rs.stringForColumn("price") as NSString).floatValue
tempModel.shop_id = rs.stringForColumn("shop_id")
tempModel.shop_name = rs.stringForColumn("shop_name")
tempModel.sku_id = Int(rs.intForColumn("sku_id"))
tempModel.item = Int(rs.intForColumn("item"))
let sku_dic:NSArray = try! NSJSONSerialization.JSONObjectWithData(rs.dataForColumn("sku_dic"), options: NSJSONReadingOptions.MutableContainers) as! NSArray
tempModel.sku_dic = sku_dic
}
if tempModel.ID == nil {
db.close()
return nil
}else{
db.close()
return tempModel
}
}else{
db.close()
return nil
}
}
///获取所有的数据
func getShopCarCatch()->NSMutableArray?{
let sql = "SELECT * FROM ShopCar_Sqlite WHERE keyID >= ?"
let db = self.getDb()
db.open()
let array = NSMutableArray()
let rs = db.executeQuery(sql, withArgumentsInArray: [0])
while rs.next() {
let model:ShoppingCartModel = ShoppingCartModel()
model.imgurl = rs.stringForColumn("imgurl")
model.describe = rs.stringForColumn("describe")
model.ID = Int(rs.intForColumn("ID"))
model.number = Int(rs.intForColumn("number"))
model.price = (rs.stringForColumn("price") as NSString).floatValue
model.shop_id = rs.stringForColumn("shop_id")
model.shop_name = rs.stringForColumn("shop_name")
model.sku_id = Int(rs.intForColumn("sku_id"))
model.item = Int(rs.intForColumn("item"))
let sku_dic:NSArray = try! NSJSONSerialization.JSONObjectWithData(rs.dataForColumn("sku_dic"), options: NSJSONReadingOptions.MutableContainers) as! NSArray
model.sku_dic = sku_dic
array.addObject(model)
}
db.close()
return array
}
///删除数据库文件
func deleteFile(){
//tip:此处直接把数据库文件删除了,可以用sq语句只删除表单
let fileManage = NSFileManager.defaultManager()
let databasePath = "/ShopCar_Sqlite.db".documentPath()
if fileManage.fileExistsAtPath(databasePath) {
try! fileManage.removeItemAtPath(databasePath)
}
}
}