昨天講完如何刪除資料,今天來說明如何修改資料吧!
修改資料的SQL語法
    // 修改資料
    func updateData(id: String, name: String, age: Int){
        if self.connectDB() {
            let updateData = "UPDATE RESUME SET name = ?, age = ? WHERE id = ?"
            do {
                try self.database.executeUpdate(updateData, values: [name,age,id])
            } catch {
                print(error.localizedDescription)
            }
            self.database.close()
        }
    }
首先新增一個單例來儲存要修改的那筆資料
class ResumeSingleton{
    static let shared = ResumeSingleton()
    var id: String = ""
    var name: String = ""
    var age: Int = 0
}
在昨天宣告的protocol extension的details加上程式碼,讓選擇的該筆資料儲存於單例內
extension MainVC: ResumeTableViewCellListener{
    func buttonClicked(buttonType: String, index: Int) {
        switch buttonType {
        case "details" :
            ResumeSingleton.shared.id = resumeList[index].id
            ResumeSingleton.shared.name = resumeList[index].name
            ResumeSingleton.shared.age = resumeList[index].age
            let nextVC = EditVC()
            self.navigationController?.pushViewController(nextVC, animated: false)
        case "delete" :
            Database.shared.deleteData(id: resumeList[index].id)
            self.fetchData()
        default:
            break
        }
        
    }
}
跳頁後,讓修改資料的TextField內文字等於單例儲存的值
func setTextField(){
        nameTextField.text = ResumeSingleton.shared.name
        ageTextField.text = String(ResumeSingleton.shared.age)
}
按下修改按鈕後進行修改的動作
    @IBAction func updateData(_ sender: Any) {
        Database.shared.updateData(id: id, name: nameTextField.text!, age: Int(ageTextField.text!) ?? 10)
        let alert = UIAlertController(title: "", message: "修改資料成功", preferredStyle: .alert)
        let okaction = UIAlertAction(title: "確認", style: .default) { action in
            self.navigationController?.popViewController(animated: false)
        }
        alert.addAction(okaction)
        self.present(alert, animated: false, completion: nil)
    }
在畫面消失時,讓單例的值初始化
override func viewWillDisappear(_ animated: Bool) {
        ResumeSingleton.shared.id = ""
        ResumeSingleton.shared.name = ""
        ResumeSingleton.shared.age = 0
}


如此一來就成功修改資料啦!
明天會講這次FMDB練習最後的指令-查詢資料