目录
学习笔记,写到哪是哪。
接着上一篇文章:Go语学习笔记 - gorm使用 - 表增删改查 | Web框架Gin(八)_剑客阿良_ALiang的博客-CSDN博客
基本的数据库操作都OK了,本篇主要对一些原生SQL使用、命名参数、Rows遍历、ToSQL生成SQL测试语句等功能做接口使用测试。
项目地址:github地址
在实际项目中,在一些复杂sql语句来做查询等操作的时候,会使用到原生sql语句来实现。
先看一下Raw方法的使用,在student_service下新增SelectOutline方法。
方法代码如下:
- //查询所有学生简述信息
- func (t StudentImpl) SelectOutline() rsp.ResponseMsg {
- log.Logger.Info("查询所有学生简述信息")
- _db := mysql.GetDB()
- var _result []constants.StudentOutline
- _db.Raw("select id,name,age from student where del_flag = 0").Scan(&_result)
- return *rsp.SuccessMsg(_result)
- }
通过Raw方法可以直接执行sql语句,并将结果赋值到对应的指针地址。
使用Exec可以简单粗暴的直接执行语句,不处理返回值。
在student_service下新增UpdateExec方法。
方法代码如下:
- //使用exec进行数据更新
- func (t StudentImpl) UpdateExec(req req.StudentUpdateExecReq) rsp.ResponseMsg {
- log.Logger.Info("使用exec模式数据更新")
- _db := mysql.GetDB()
- _db.Exec("UPDATE student SET name = ? WHERE id = ?", req.Name, req.Id)
- return *rsp.SuccessMsg("更新成功")
- }
可以看到语句中使用“?”作为参数占位符。
GORM 支持 sql.NamedArg、map[string]interface{}{} 或 struct 形式的命名参数。
在student_service下新增SelectByNamespace方法。
方法代码如下:
- //使用命名参数查询
- func (t StudentImpl) SelectByNamespace(age int64) rsp.ResponseMsg {
- log.Logger.Info("使用命名参数查询")
- _db := mysql.GetDB()
- var students []db_entity.Student
- _db.Where("age > @name and del_flag = @name2", sql.Named("name", age), sql.Named("name2", 0)).Find(&students)
- return *rsp.SuccessMsg(students)
- }
使用@args方式命名参数,后面使用sql.Named方法对参数传值。
GORM可以通过ToSQL方法生成需要执行的sql语句。
在student_service下新增GetSql方法。
方法代码如下:
- //获取Sql语句
- func (t StudentImpl) GetSql() rsp.ResponseMsg {
- log.Logger.Info("获取sql语句")
- _db := mysql.GetDB()
- _sql := _db.ToSQL(func(tx *gorm.DB) *gorm.DB {
- return tx.Model(&db_entity.Student{}).Where("id > ?", 0).Limit(2).Order("age desc").Find(&[]db_entity.Student{})
- })
- fmt.Printf("sql is > %s\n", _sql)
- return *rsp.SuccessMsg("获取成功")
- }
同样支持占位符来构建SQL。
在获取到查询数据,我们需要对数据进行遍历。可以使用Rows方法。
在student_service下新增TestRow方法。
方法代码如下:
- //测试row遍历方式
- func (t StudentImpl) TestRow() rsp.ResponseMsg {
- log.Logger.Info("测试row遍历方式")
- _db := mysql.GetDB()
- var (
- _id int32
- _name string
- _age int64
- )
- _rows, _err := _db.Raw("select id,name,age from student where del_flag = 0").Rows()
- if _err != nil {
-
- log.Logger.Panic("执行sql异常", log.Any("error", _err.Error()))
- }
- defer _rows.Close()
- for _rows.Next() {
- _rows.Scan(&_id, &_name, &_age)
- fmt.Printf("student -> id=%v,name=%v,age=%v\n", _id, _name, _age)
- }
- return *rsp.SuccessMsg("测试成功")
- }
controller层增加接口代码,如下:
- //查询所有学生简述
- func (s StudentController) SelectOutline(context *gin.Context) {
- log.Logger.Info("SelectOutline接口")
- _rsp := services.StudentServ.SelectOutline()
- context.JSON(http.StatusOK, _rsp)
- }
-
- //使用exec进行数据更新
- func (s StudentController) UpdateExec(context *gin.Context) {
- log.Logger.Info("UpdateExec接口")
- var studentUpdateExecReq req.StudentUpdateExecReq
- if err := context.ShouldBindJSON(&studentUpdateExecReq); err != nil {
- log.Logger.Panic("参数异常")
- }
-
- if _, err := json.Marshal(studentUpdateExecReq); err != nil {
- log.Logger.Panic("参数解析异常")
- }
- _rsp := services.StudentServ.UpdateExec(studentUpdateExecReq)
- context.JSON(http.StatusOK, _rsp)
- }
-
- //使用命名参数查询
- func (s StudentController) SelectByNamespace(context *gin.Context) {
- log.Logger.Info("SelectByNamespace接口")
- _age := context.Query("age")
- _a, _ := strconv.ParseInt(_age, 10, 64)
- _rsp := services.StudentServ.SelectByNamespace(int64(_a))
- context.JSON(http.StatusOK, _rsp)
- }
-
- //获取sql语句
- func (s StudentController) GetSql(context *gin.Context) {
- log.Logger.Info("获取sql语句接口")
- _rsp := services.StudentServ.GetSql()
- context.JSON(http.StatusOK, _rsp)
- }
-
- //测试row遍历方式
- func (s StudentController) TestRow(context *gin.Context) {
- log.Logger.Info("测试row遍历方式接口")
- _rsp := services.StudentServ.TestRow()
- context.JSON(http.StatusOK, _rsp)
- }
router增加路由路径,如下:
- r.GET("/student/selectOutline", controllers.StudentCtrl.SelectOutline)
- r.POST("/student/updateExec", controllers.StudentCtrl.UpdateExec)
- r.GET("/student/selectByNamespace", controllers.StudentCtrl.SelectByNamespace)
- r.GET("/student/getSql", controllers.StudentCtrl.GetSql)
- r.GET("/student/testRow", controllers.StudentCtrl.TestRow)
分别验证一下接口
/student/selectOutline

/student/updateExec

/student/selectByNamespace

/student/getSql


/student/testRow


分享:
人的一切痛苦,本质上都是对自己的无能的愤怒。——王小波
