SQLite.swift了解

    import UIKit
    import SQLite

    class ViewController: UIViewController {
        
        var db:Connection! = nil
        var users = Table("users")
        var id = Expression("id")
        var name = Expression("name") // 可以为空
        var email = Expression("email")

        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            do {
                db = try Connection(NSHomeDirectory()+"/Documents/dbsss.swift")
                try db.run(users.create(block: { (tabl) in
                    tabl.column(id, primaryKey:true) // 主键
                    tabl.column(name)
                    tabl.column(email,unique: true)
                }))
            } catch {
                print(error)
            }
            
        }
        
        @IBAction func addAction(_ sender: UIButton) {
            // 直接输入值
    //        do {
    //            let insert = users.insert(name<-"yujinhai",email<-"[email protected]")
    //            try db.run(insert)
    //        } catch {
    //            print(error)
    //        }
            // c语言写法
            do {
                let stmt = try db.prepare("INSERT INTO users (email) VALUES (?)")
                for email in [" [email protected]", "[email protected]","[email protected]"] {
                    try stmt.run(email)
                }
            } catch {
                print(error)
            }
            
            
        }
        
        @IBAction func deleteAction(_ sender: UIButton) {
            let deleteValue = users.filter(id == 2)
            do {
                try db.run(deleteValue.delete())
            } catch {
                print(error)
            }
        }
        @IBAction func searchAction(_ sender: UIButton) {
            do {
                for value in try db.prepare(users) {
                    print("id:\(value[id]),name:\(value[name]),email:\(value[email])")
                }
            } catch {
                print(error)
            }
    //
            
    //        do {
    //            for row in try db.prepare("SELECT id, email FROM users") {
    //                print("id: \(row[0]), email: \(row[1])")
    //            }
    //        } catch {
    //            print(error)
    //        }
            
            
    //        do {
    //            let value = try db.scalar("SELECT count(*) FROM users")
    //            print("value:\(value)")
    //        } catch {
    //            print(error)
    //        }
            
        }
        @IBAction func changeAction(_ sender: UIButton) {
        
            let changeValue = users.filter(id == 2)
            do {
                try db.run(changeValue.update(name<-name.replace("yujinhai", with: "yjh")))
            } catch {
                print(error)
            }
        }
        
    }

你可能感兴趣的:(SQLite.swift了解)