美文网首页Golang入坑之旅
modules用户查询和处理数据库关系

modules用户查询和处理数据库关系

作者: 写写而已 | 来源:发表于2019-10-08 18:28 被阅读0次
    package models
    
    // import "fmt"
    import(
        . "../../database"
        "fmt"
        //"github.com/gin-gonic/gin"
        "log"
        //"net/http"
    )
    // import "time"
    // import "log"
    // 学生表模型
    type Students struct {
        ID int `db:"id"`
        Name string  `db:"name"`
        // Page string `"page"`
    }
    
    func (p *Students) GetStudents(page int) (students []Students, err error) {
        students = make([]Students, 0)
        rows, err := SqlDB.Query("select id, name from students limit ?,10", (page - 1) * 10)
        defer rows.Close()
        if err != nil {
            return
        }
        for rows.Next() {
            var person Students
            rows.Scan(&person.ID, &person.Name)
            students = append(students, person)
        }
        if err = rows.Err(); err != nil {
            return
        }
        return
    }
    
    //学生信息模型
    type StudentInfo struct {
        ID int `db:"id"`
        Name string `db:"name"`
        Score float32 `db:"score"`
        Enabled int `db:"enabled"`
    }
    func (p *StudentInfo) GetStudentById(id string) (student StudentInfo, err error) {
        // var student StudentInfo
        // fmt.Println(id)
        row := SqlDB.QueryRow("select id, name, score, enabled from students where id = ?", id)
        // defer row.Close()
        row.Scan(&student.ID, &student.Name, &student.Score, &student.Enabled)
        // fmt.Println(student)
        // student = row
        if err != nil {
            return
        }
        return
    }
    
    //新增学生信息
    func (p *StudentInfo) ConfirmStudent(data StudentInfo) (id int64, err error) {
        rs, err := SqlDB.Exec("INSERT INTO students(name, score) VALUES (?, ?)", data.Name, data.Score)
    
        if err != nil {
            log.Fatalln(err)
        }
        id, err = rs.LastInsertId()
        if err != nil {
            log.Fatalln(err)
        }
        fmt.Println("insert person Id is", id)
        if err != nil{
            return
        }
        return
    }
    

    相关文章

      网友评论

        本文标题:modules用户查询和处理数据库关系

        本文链接:https://www.haomeiwen.com/subject/enhipctx.html