iOS中如果本地缓存数据库使用的SQLite,绝大数人都使用了FMDB,可以算是标配.如果自己对SQLite原生态的开发方式效率太低,使用FMDB会有种鸟枪换炮的感觉.FMDB相比于原生态的SQLite的查询做出了很多优化,查询更新方法非常简单易用.
FMDB配置
新建Swift项目,下载FMDB项目,将以下四个文件添加至新的项目中:
数据库初始化:
class DataManager {
static let shareIntance:DataManager = DataManager()
var db:FMDatabase = FMDatabase()
func createDataBase(dataName:String) {
let path:String = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0]
let finalPath:String = path.appending("/\(dataName)")
print("数据存储地址:\(finalPath)")
db = FMDatabase(path: finalPath)
if db.open() {
print("数据库打开成功")
}
}
}
订单表中相比之前变化不大,查询方法有所优化:
class Order {
var db:FMDatabase = DataManager.shareIntance.db
var orderName:String = ""
var orderNumber:Int = 0
// 创建订单表
func createTable() {
let createTableSQL = "CREATE TABLE IF NOT EXISTS 't_order' ('id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,'orderName' TEXT,'orderNumber' INTEGER);"
let result = db.executeUpdate(createTableSQL, withArgumentsIn: nil)
if result {
print("创建表格成功")
}
}
// MARK:- 插入数据
func insertOrder() {
let insertSQL = "INSERT INTO t_order (orderName, orderNumber) VALUES (\"\(self.orderName)\", \(self.orderNumber));"
let result = db.executeUpdate(insertSQL, withArgumentsIn: nil)
if result {
print("数据新增成功")
}
}
func searchData() {
let querySQL = "SELECT * FROM t_order"
var resultSet:FMResultSet?
do {
try resultSet = db.executeQuery(querySQL, values: nil)
while (resultSet?.next())! {
let name = resultSet?.string(forColumn: "orderName")
let number = resultSet?.int(forColumn: "orderNumber")
print("订单编号:\(number!)--订单名称:\(name!)")
}
} catch {
}
}
func deleteData() {
let deleteSQL = "DELETE FROM t_order WHERE id = 1"
let result = db.executeUpdate(deleteSQL, withArgumentsIn: nil)
if result {
print("数据删除成功")
}
}
func updateData() {
let updateSQL = "UPDATE t_order SET orderName = '花生' WHERE id = 1"
let result = db.executeUpdate(updateSQL, withArgumentsIn: nil)
if result {
print("修改成功")
}
}
}
实际测试
关于字段SQL语句网上有很多,基本上差别不大,完全看自己的业务情况,通过简单查询,删除,更新来验证代码:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let dataManager:DataManager = DataManager.shareIntance
dataManager.createDataBase(dataName: "FlyElephant.sqlite")
let order = Order()
order.createTable()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func addAction(_ sender: UIButton) {
for i in 0...10 {
let order:Order = Order()
order.orderNumber = i
order.orderName = "FlyElephant-\(i)"
order.insertOrder()
}
}
@IBAction func updateAction(_ sender: UIButton) {
let order:Order = Order()
order.updateData()
}
@IBAction func searchAction(_ sender: UIButton) {
let order:Order = Order()
order.searchData()
}
@IBAction func deleteAction(_ sender: UIButton) {
let order:Order = Order()
order.deleteData()
}
测试结果如下: