1 添加依赖
pod 'WCDB.swift' #数据库
2 使用的页面引入
import WCDBSwift
3 创建db
//
// WCDBUtil.swift
// BookKeeping
//
// Created by gy on 2022/12/7.
//
import Foundation
import WCDBSwift
class WCDBUtil {
//静态变量定义单例
static let share = WCDBUtil()
public var dataBase : Database? = nil
private var dbName: String = "bookKeeping"
//禁止构造
private init(){}
//链接数据库
public func connectDatabase(){
if(dataBase != nil){
dataBase?.close()
}
guard let fileURL = try? FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent(dbName) else { return }
debugPrint("数据库路径:",fileURL)
dataBase = Database(withFileURL: fileURL)
createTabs()
}
private func createTabs(){
try? dataBase?.create(table: "category", of: CategoryEntity.self)
}
}
4 创建实体类(表信息)
注意点
1 如果某些字段在查询的时候不需要,那么需要设置成可选的
2 isAutoIncrement 如果设置了主键,那么这个属性要开启 比如 id 我们一般不自己设置 都开启自增
//
// Category.swift
// BookKeeping
//
// Created by gy on 2022/12/7.
//
import Foundation
import WCDBSwift
class CategoryEntity : TableCodable {
//如果查询的时候 可能不需要这个字段 那么这个字段需要设置成可选的
var id: Int? = 0
var title:String = ""
//标签类型 0(支出)/1(收入)
var categoryType:Int? = 0
enum CodingKeys: String, CodingTableKey {
typealias Root = CategoryEntity
static let objectRelationalMapping = TableBinding(CodingKeys.self)
case id
case title
case categoryType
//字段限制
static var columnConstraintBindings: [CodingKeys: ColumnConstraintBinding]? {
return [
id: ColumnConstraintBinding(isPrimary: true,isAutoIncrement: true,isNotNull : true, defaultTo: 0)
]
}
}
//如果设置了主键 这个就得设置 比如 id 我们一般不自己设置 都开启自增
var isAutoIncrement: Bool = true // 用于定义是否使用自增的方式插入
}
5 插入数据
@objc
private func saveCategory(){
let categoryTitle = categoryInput.text ?? ""
let type = selectedIndex
let category = CategoryEntity()
category.title = categoryTitle
category.categoryType = 1
do {
try WCDBUtil.share.dataBase?.insert(objects: category, intoTable: "category")
print("insert==success")
let a : [CategoryEntity]? = try WCDBUtil.share.dataBase?.getObjects( fromTable: "category")
a?.forEach({ item in
print("category==",item.categoryType,item.title,item.id)
})
}catch{
print("inserterror==\(error)")
}
}