当前位置:网站首页>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


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

边栏推荐
- PTA TIANTI game exercise set l2-003 moon cake test point 2, test point 3 Analysis
- PTA ladder game exercise set l2-002 linked list de duplication
- 目标检测中的损失函数与正负样本分配:RetinaNet与Focal loss
- Common skills and understanding of SQL optimization
- Modes of optical fiber - single mode and multimode
- [cloud native] what is the microservice architecture?
- Add salt and pepper noise or Gaussian noise to the picture
- Educational Codeforces Round 22 B. The Golden Age
- Five core elements of architecture design
- Distributed global ID generation scheme
猜你喜欢

Modes of optical fiber - single mode and multimode

SAP ABAP BDC (batch data communication) -018

What is dependency injection (DI)

集群、分布式、微服务的区别和介绍
![SQLSTATE[HY000][1130] Host ‘host. docker. internal‘ is not allowed to connect to this MySQL server](/img/05/1e4bdddce1e07f7edd2aeaa59139ab.jpg)
SQLSTATE[HY000][1130] Host ‘host. docker. internal‘ is not allowed to connect to this MySQL server

Why does the data center need a set of infrastructure visual management system

Determine whether the file is a DICOM file

Differences and introduction of cluster, distributed and microservice

消息队列:如何确保消息不会丢失
![Paper reading [semantic tag enlarged xlnv model for video captioning]](/img/e3/633f6aac7a51ad7b3dc0e45dbe1f60.png)
Paper reading [semantic tag enlarged xlnv model for video captioning]
随机推荐
Get the way to optimize the one-stop worktable of customer service
Bat instruction processing details
PTA TIANTI game exercise set l2-003 moon cake test point 2, test point 3 Analysis
Flinksql 读写pgsql
Nvisual network visualization
关于服装ERP,你知道多少?
pytorch_ 01 automatic derivation mechanism
Flinksql read / write PgSQL
C#可空类型
Red Hat安装内核头文件
Hcip seventh operation
WEB架构设计过程
[daily training -- Tencent selected 50] 292 Nim games
I didn't know it until I graduated -- the principle of HowNet duplication check and examples of weight reduction
目标检测中的BBox 回归损失函数-L2,smooth L1,IoU,GIoU,DIoU,CIoU,Focal-EIoU,Alpha-IoU,SIoU
Hcip eighth operation
make makefile cmake qmake都是什么,有什么区别?
SQL query: subtract the previous row from the next row and make corresponding calculations
Nodejs get client IP
Flask1.1.4 Werkzeug1.0.1 源码分析:启动流程