当前位置:网站首页>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
小结
分享:
人的一切痛苦,本质上都是对自己的无能的愤怒。——王小波
边栏推荐
- Educational Codeforces Round 22 B. The Golden Age
- 关于服装ERP,你知道多少?
- PTA ladder game exercise set l2-002 linked list de duplication
- 盘点国内有哪些EDA公司?
- Classic questions about data storage
- 《HarmonyOS实战—入门到开发,浅析原子化服务》
- 搞懂fastjson 对泛型的反序列化原理
- 牙齿干细胞的存储问题(未完待续)
- Input of native applet switches between text and password types
- yarn入门(一篇就够了)
猜你喜欢
上海字节面试问题及薪资福利
Randomly generate session_ id
Distributed global ID generation scheme
毕业之后才知道的——知网查重原理以及降重举例
Interview questions and salary and welfare of Shanghai byte
数据中心为什么需要一套基础设施可视化管理系统
《2022中国低/无代码市场研究及选型评估报告》发布
Red Hat安装内核头文件
Get the way to optimize the one-stop worktable of customer service
R语言【逻辑控制】【数学运算】
随机推荐
WEB架构设计过程
make makefile cmake qmake都是什么,有什么区别?
成为资深IC设计工程师的十个阶段,现在的你在哪个阶段 ?
PTA 天梯赛练习题集 L2-002 链表去重
2pc of distributed transaction solution
爬虫练习题(三)
Mybaits multi table query (joint query, nested query)
STM32按键状态机2——状态简化与增加长按功能
Go 語言的 Context 詳解
Sidecar mode
Hcip eighth operation
What is message queuing?
Message queue: how to deal with message backlog?
Pytorch builds neural network to predict temperature
Common skills and understanding of SQL optimization
Simple case of SSM framework
C#可空类型
数字IC面试总结(大厂面试经验分享)
Explication contextuelle du langage Go
Win configuration PM2 boot auto start node project