SwiftUI一起学之七 -- Sqlite数据库

一 学习目标

学会操作数据库,完成新增,删除,查询功能

二 学习效果

image.png

三 主要操作步骤

3.1 使用Swift Package Manager添加SQLite.swift库

SQLite.swift库的地址: https://github.com/stephencelis/SQLite.swift

image.png

3.2 创建数据库

private var db:Connection?

let path = NSSearchPathForDirectoriesInDomains(
                .documentDirectory, .userDomainMask, true
                ).first!
db = try! Connection("\(path)/db.sqlite3")
db?.busyTimeout = 5.0

3.3 创建表

private var usersTable:Table?
let id_column = Expression("id")
let name_column = Expression("name")

usersTable = Table("records")
try! getDB().run(
    usersTable!.create (ifNotExists: true, block:{ t in
            t.column(id_column, primaryKey: true)
            t.column(name_column, unique: true)
          })
)

3.4 新增数据

let insert = usersTable.insert(name_column <- name)
if let rowId = try? db.run(insert) {
    print("插入成功:\(rowId)")
    return true
} else {
    print("插入失败")
    return false
}

3.5 删除数据

let alice = usersTable.filter(Expression("name") == user.name!)
if let count = try? db.run(alice.delete()) {
    return count>0
} else {
    return false
}

3.6 查询数据

let query = usersTable.order(id_column.desc)
        
do {
    let results = try db.prepare(query);

    for userRow in results {
        print("name = \(userRow[name_column])")
    }
} catch {
    print("出错")
}
return users;

四 完整项目代码

4.1 SwiftUiDemo.swift

import SwiftUI

struct SqliteUIView: SwiftUI.View  {
    @ObservedObject var sqliteViewModel = SqliteViewModel.single
    @State private var showingAlert = false
    @State var userName:String = ""
    @State var users: [UserModel] = []
    
    var body: some SwiftUI.View  {
        VStack{
            Text("用户数据库").font(.system(size:20))
            HStack{
                // 输入框
                TextField("输入用户名", text: $userName)
                    .padding(EdgeInsets(top: 5, leading: 20, bottom: 5, trailing: 20))
                    .background(Color.yellow)
                    .cornerRadius(10)
                    .frame(width: 150)
                // 插入
                Button.init("新增") {
                    let success = sqliteViewModel.insert(name: userName)
                    if(success){
                        // 成功插入后查询
                        users = sqliteViewModel.getUsers()
                        print(users)
                    }
                }
                .padding(EdgeInsets(top: 5, leading: 20, bottom: 5, trailing: 20))
                .background(Color.green)
                .cornerRadius(20)
                // 查询
                Button.init("查询") {
                    users = sqliteViewModel.getUsers()
                }
                .padding(EdgeInsets(top: 5, leading: 20, bottom: 5, trailing: 20))
                .background(Color.green)
                .cornerRadius(20)
            }
            // 列表
            List(users){ user in
                UserRow(user: user){ _ in
                    // 删除
                    let success = SqliteViewModel.single.delete(user: user)
                    if(success){
                        // 成功插入后查询
                        users = sqliteViewModel.getUsers()
                        print(users)
                    }
                }
            }
        }.onAppear {
            users = sqliteViewModel.getUsers()
        }
    }
}

// 列表项
struct UserRow: View {
    var user: UserModel
    var deleteCb:(_ user:UserModel)->()
    
    var body: some View {
        HStack{
            Text("用户名 =  \(user.name!)")
            Spacer()
            Button.init("删除") {
                deleteCb(user)
            }
            .padding(EdgeInsets(top: 5, leading: 20, bottom: 5, trailing: 20))
            .background(Color.red)
            .cornerRadius(20)
        }
    }
}

4.2 SqliteViewModel.swift

import Foundation
import SQLite

let id_column = Expression("id")
let name_column = Expression("name")

class SqliteViewModel: ObservableObject {
    static let single = SqliteViewModel()
    
    private var db:Connection?
    private var usersTable:Table?
    
    func getDB() -> Connection {
        if db == nil {
            let path = NSSearchPathForDirectoriesInDomains(
                .documentDirectory, .userDomainMask, true
                ).first!
            db = try! Connection("\(path)/db.sqlite3")
            db?.busyTimeout = 5.0
        }
        return db!
    }
    
    func getUserTable() -> Table {
        if usersTable == nil {
            usersTable = Table("records")
            try! getDB().run(
                usersTable!.create (ifNotExists: true, block:{ t in
                    t.column(id_column, primaryKey: true)
                    t.column(name_column, unique: true)
                })
            )
        }
        return usersTable!
    }
    
    // 增加
    func insert(name:String) -> Bool{
        let insert = getUserTable().insert(name_column <- name)
        if let rowId = try? getDB().run(insert) {
            print("插入成功:\(rowId)")
            return true
        } else {
            print("插入失败")
            return false
        }
    }
    
    // 查询
    func getUsers() -> [UserModel]{
        var users: [UserModel] = []
        users.removeAll()
        let query = getUserTable().order(id_column.desc)
        
        do {
            let results = try getDB().prepare(query);
            
            for userRow in results {
                print("name = \(userRow[name_column])")
                let user = UserModel(name: userRow[name_column])
                users.append(user)
            }
        } catch {
            print("出错")
        }
        return users;
    }
    
    // 删除
    func delete(user:UserModel)-> Bool{
        let alice = getUserTable().filter(Expression("name") == user.name!)
        if let count = try? getDB().run(alice.delete()) {
            return count>0
        } else {
            return false
        }
    }
}

4.3 Model.swift

import Foundation

struct UserModel: Identifiable {
    var id = UUID()
    var email : String?
    var name : String?
}

参考:

  1. SQLite.swift

你可能感兴趣的:(SwiftUI一起学之七 -- Sqlite数据库)