做一个小小的分享,你要有基本的Sqlite知识哦
头文件的引用
创建桥接文件的方法前面文章中有叙述,这里就不在重复,在桥接header中添加
#import <FMDB/FMDB.h>
但是在dataManager中声明FMDatabase时仍然不行,所以我又在Manager所在在类里面添加
import FMDB
单列及库表创建
创建相关表单和属性,直接上demo
public static let localManager :LocalDataManager = LocalDataManager()
var fmdb: FMDatabase?
override init() {
super.init()
self.creatDataBase(name: "******LocalData.db")
}
func creatDataBase(name: String) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let dbPath = documentsPath + name
fmdb = FMDatabase(path:dbPath)
if fmdb?.open() == false {
print("打开数据库失败")
return
}
creatTable()
}
func creatTable() {
//浏览记录
let sql1 = "create table if not exists ******Tabel(itemId primary key not null,sellPrice not null,image not null, name not null,date not null);"
_ = fmdb!.executeUpdate(sql1, withArgumentsIn: nil)
}
结构搭建
用extension来区分表的操作
//*****记录
extension LocalDataManager {
}
//***信息
extension LocalDataManager {
}
//***列表
extension LocalDataManager {
}
增、删、改、查
简单的代码
func insertShop(shop:CartShop) {
_ = fmdb?.executeUpdate("insert into shop(SysNo, ShopSysNo, ShopName) values(?,?,?);", withArgumentsIn: [shop.SysNo!, shop.ShopSysNo!, shop.ShopName!])
}
func updateShop(shop:CartShop) {
fmdb?.executeUpdate("update newOrderTabel set SysNo=?, ShopSysNo=?, ShopName=?", withArgumentsIn: [shop.SysNo!, shop.ShopSysNo!, shop.ShopName!])
}
func isExsitShop(shop:CartShop) -> Bool {
let rs = fmdb?.executeQuery("SELECT * FROM shop WHERE SysNo=?", withArgumentsIn: [shop.SysNo!])
if rs != nil && rs!.next() {
return true
}
return false
}
func fetchAllShop() -> [CartShop] {
let rs = fmdb?.executeQuery("SELECT * FROM shop", withArgumentsIn: nil)
}