当前位置:网站首页>Swiftui basic learning journal (XI) SQLite data operation

Swiftui basic learning journal (XI) SQLite data operation

2022-06-21 22:37:00 Mobile terminal development_ Xiaohei

Keep creating , Accelerate growth ! This is my participation 「 Nuggets day new plan · 6 Yuegengwen challenge 」 Of the 20 God , Click to see the event details

Hello everyone , I'm Xiaohei , A programmer who's not bald yet ~~~

Life is too short , You know, regret is more terrible than failure

What I want to introduce today is SwiftUI For manipulating data in sqlite library , It and core It is also used for data access , But I'm right about sql The data is quite friendly , So let's first introduce how to use sqlite Library for data operations , The effect can refer to my previous articles : iOS- be based on SwiftUI Simple memo for development , Suitable for newcomers to learn This is a simple memo app, Suitable for newcomers to learn , Don't talk much , To the body :

SQLite.swift It is also a lightweight 、 Yes swift Amicable C Language wrapper API.

( One ) Add dependency

First in swift package Add sqlite The remote repository

image.png

( Two )model

Prepare an implementation Identifiable The entity class of the protocol , take ID Set to uuid, This ensures that the value is unique , If it's done Identifiable But none of the attributes are unique , Will be an error , I forgot the screenshot here , You can try it yourself , The entity class code is as follows :

struct NoteModel: Identifiable{
    var id = UUID()
    var title : String=""
    var content : String=""
    var createTimeStamp:String="0"
    var updateTimeStamp:String="0"
    
}

( 3、 ... and )Dao

Prepare a tool class to operate on the data table corresponding to this entity , act as Dao Layer action

newly added

 func insert(note:NoteModel) -> Bool{
            let insert = getNoteTable().insert(id_column<-note.id,title_column <- note.title,content_column<-note.content,create_time_stamp_column<-note.createTimeStamp,update_time_stamp_column<-note.updateTimeStamp)
            if let rowId = try? getDB().run(insert) {
                print(" Insert the success :\(rowId) Bar record ")
                getNotes(keyWord: searchContent, orderby: orderbyIndex)
                return true
            } else {
                print(" Insert the failure ")
                return false
            }
        }

Delete

func delete( note:NoteModel) -> Bool{
        let deleteCmd = getNoteTable().filter(Expression<UUID>("id") == note.id)
        if let count = try? getDB().run(deleteCmd.delete()) {
            return count>0
        
        } else {
            return false
        }
    }

there filter Be similar to sql Statement where Inquire about

modify

func update(note:NoteModel) -> Bool {
        let updateCmd=getNoteTable().filter(id_column==note.id).update(id_column<-note.id,title_column <- note.title,content_column<-note.content,update_time_stamp_column<-Date().milliStamp)
        print(updateCmd)
        if let rowId = try? getDB().run(updateCmd) {
            print(" The update is successful :\(rowId) Bar record ")
            getNotes(keyWord: searchContent, orderby: orderbyIndex)
            return true
        } else {
            print(" Update failed ")
            return false
        }
        
    }

filter amount to where The role of ,update Middle represents assigning a value to the corresponding column

Inquire about

 //  Inquire about 
    func getNotes(keyWord:String,orderby:Int) -> Void{
        self.searchContent=keyWord
        self.orderbyIndex=orderby
        var orderby2:SQLite.Expressible
        switch orderby {
        case 0:
            orderby2=create_time_stamp_column.desc
        case 1:
            orderby2=update_time_stamp_column.desc
        default:
            orderby2=title_column.desc
        }
        let query = getNoteTable().order(orderby2).where(title_column.like("%\(keyWord)%")||content_column.like("%\(keyWord)%"))
            print(query)
            do {
                noteList.removeAll()
                let results = try getDB().prepare(query);
                
                for noteRow in results {
                    let note = NoteModel(id: noteRow[id_column], title: noteRow[title_column], content: noteRow[content_column], createTimeStamp: noteRow[create_time_stamp_column], updateTimeStamp: noteRow[update_time_stamp_column])
            
                    noteList.append(note)
                }
                print(" The query is successful ")
                
            } catch {
                print(" error ")
            }
        }

The query here uses where function , As filter ,where The function uses like function , amount to sql Fuzzy query in statement ,|| perhaps && amount to sql Statement or perhaps and Inquire about , And then finally you can call desc Indicates reverse order query

Field column

The code that defines the column is as follows :

let id_column = Expression<UUID>("id")
let title_column=Expression<String>("title")
let content_column=Expression<String>("content")
let create_time_stamp_column=Expression<String>("createTimeStamp")
let update_time_stamp_column=Expression<String>("updateTimeStamp")

The above is swift About China sqlite Use , Today's swiftUI That's all for learning and sharing , I will continue to output iOS Development Notes , Thanks for reading ! Joint efforts !

原网站

版权声明
本文为[Mobile terminal development_ Xiaohei]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206212043480283.html