面向对象创建数据库

github数据库框架引用:https://github.com/stephencelis/SQLite.swift

注:对系统的sqlite数据库封装,所以需要加上libsqlite3.tbd

    let path = Bundle.main.path(forResource: "test", ofType: ".db")
        print(path!)
        let db = try! Connection(path!)
//        let resultCode = try! db.execute("create table t_user ('id' INTEGER PRIMARY KEY NOT NULL, 'name' TEXT, 'email' TEXT NOT NULL UNIQUE)")
//        print(resultCode)
        
        //第二步:面向对象编程创建表(表->对象)
        //1、创建表->对象:Table
        let table = Table("t_student")
        //2、创建子段(子段->对象)
        let id = Expression("id")
        let name = Expression("name")
        let email = Expression("email")
        //3、给表添加子段
        let sql = table.create { (t) in
            //添加id子段
            t.column(id, primaryKey: true)
            //添加name子段
            t.column(name)
            //添加email子段
            t.column(email)
        }
        print(sql)
        //4、执行sql
        try! db.run(sql)
        
        //第三步:插入数据->SQL面向对象
        //1、创建插入SQL
        let sqlInsert = table.insert(id <- 1, name <- "校长", email <- "[email protected]")
        //2、执行SQL
        try! db.run(sqlInsert)
        
        //第四步:查询数据->SQL面向对象
        //1、创建查询SQL
        let sqlSelect = table.select(*)
        //2、执行SQL
        let rows = try! db.prepare(sqlSelect)
        //3、遍历数据(迭代器模式)
        for row in rows {
            print("id: \(row[id])")
            print("name: \(row[name])")
            print("email: \(row[email])")
        }

你可能感兴趣的:(面向对象创建数据库)