当前位置:网站首页>Go语学习笔记 - gorm使用 - 原生sql、命名参数、Rows、ToSQL | Web框架Gin(九)
Go语学习笔记 - gorm使用 - 原生sql、命名参数、Rows、ToSQL | Web框架Gin(九)
2022-07-07 00:38:00 【剑客阿良_ALiang】
目录
学习笔记,写到哪是哪。
接着上一篇文章:Go语学习笔记 - gorm使用 - 表增删改查 | Web框架Gin(八)_剑客阿良_ALiang的博客-CSDN博客
基本的数据库操作都OK了,本篇主要对一些原生SQL使用、命名参数、Rows遍历、ToSQL生成SQL测试语句等功能做接口使用测试。
项目地址:github地址
原生sql使用
在实际项目中,在一些复杂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方法对参数传值。
ToSQL获取sql语句
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遍历
在获取到查询数据,我们需要对数据进行遍历。可以使用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


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

边栏推荐
- 404 not found service cannot be reached in SAP WebService test
- SAP webservice 测试出现404 Not found Service cannot be reached
- 三级菜单数据实现,实现嵌套三级菜单数据
- Three level menu data implementation, nested three-level menu data
- In memory, I moved from CSDN to blog park!
- Digital IC interview summary (interview experience sharing of large manufacturers)
- Get the way to optimize the one-stop worktable of customer service
- Dynamic memory management
- 爬虫练习题(三)
- Introduction to distributed transactions
猜你喜欢

ForkJoin最全详解(从原理设计到使用图解)

Sidecar mode
![[reading of the paper] a multi branch hybrid transformer network for channel terminal cell segmentation](/img/f6/cd307c03ea723e1fb6a0011b37d3ef.png)
[reading of the paper] a multi branch hybrid transformer network for channel terminal cell segmentation

目标检测中的BBox 回归损失函数-L2,smooth L1,IoU,GIoU,DIoU,CIoU,Focal-EIoU,Alpha-IoU,SIoU

bat 批示处理详解

What is message queuing?

Red Hat安装内核头文件

Hcip seventh operation

Differences and introduction of cluster, distributed and microservice

404 not found service cannot be reached in SAP WebService test
随机推荐
Mysql-centos7 install MySQL through yum
Type de texte de commutation d'entrée et de mot de passe de l'applet natif
Data storage 3
Explication contextuelle du langage Go
AI人脸编辑让Lena微笑
Reptile exercises (III)
话说SQLyog欺骗了我!
OpenSergo 即将发布 v1alpha1,丰富全链路异构架构的服务治理能力
线性回归
Hcip seventh operation
STM32 key state machine 2 - state simplification and long press function addition
Simple case of SSM framework
Unity keeps the camera behind and above the player
《2022中国低/无代码市场研究及选型评估报告》发布
Add salt and pepper noise or Gaussian noise to the picture
力扣102题:二叉树的层序遍历
数据中心为什么需要一套基础设施可视化管理系统
[cloud native] what is the microservice architecture?
Classic questions about data storage
Différenciation et introduction des services groupés, distribués et microservices