当前位置:网站首页>Go language learning notes - Gorm use - native SQL, named parameters, rows, tosql | web framework gin (IX)
Go language learning notes - Gorm use - native SQL, named parameters, rows, tosql | web framework gin (IX)
2022-07-07 06:03:00 【Swordsman a Liang_ ALiang】
Catalog
Learning notes , Where is where .
Next to the previous article :Go English learning notes - gorm Use - Table addition, deletion, modification and query | Web frame Gin( 8、 ... and )_ Swordsman a Liang _ALiang The blog of -CSDN Blog
Basic database operations are OK 了 , This article is mainly about some native SQL Use 、 Named parameters 、Rows Traverse 、ToSQL Generate SQL Test statements and other functions to do interface use tests .
Project address :github Address
Native sql Use
In the actual project , In some complex sql Statement to do queries and other operations , Will use native sql Statement to implement .
Have a look first Raw Use of methods , stay student_service Add below SelectOutline Method .
The method code is as follows :
// Query all student brief information
func (t StudentImpl) SelectOutline() rsp.ResponseMsg {
log.Logger.Info(" Query all student brief information ")
_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)
}
adopt Raw Method can be executed directly sql sentence , And assign the result to the corresponding pointer address .
Use Exec You can simply and brutally execute statements directly , Do not process return values .
stay student_service Add below UpdateExec Method .
The method code is as follows :
// Use exec Update the data
func (t StudentImpl) UpdateExec(req req.StudentUpdateExecReq) rsp.ResponseMsg {
log.Logger.Info(" Use exec Schema data update ")
_db := mysql.GetDB()
_db.Exec("UPDATE student SET name = ? WHERE id = ?", req.Name, req.Id)
return *rsp.SuccessMsg(" The update is successful ")
}
You can see that “?” As a parameter placeholder .
Named parameters
GORM Support sql.NamedArg、map[string]interface{}{} or struct Named parameters of the form .
stay student_service Add below SelectByNamespace Method .
The method code is as follows :
// Query with named parameters
func (t StudentImpl) SelectByNamespace(age int64) rsp.ResponseMsg {
log.Logger.Info(" Query with named parameters ")
_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)
}
Use @args How to name parameters , Use... In the back sql.Named Method to pass values to parameters .
ToSQL obtain sql sentence
GORM Can pass ToSQL Method to generate what needs to be executed sql sentence .
stay student_service Add below GetSql Method .
The method code is as follows :
// obtain Sql sentence
func (t StudentImpl) GetSql() rsp.ResponseMsg {
log.Logger.Info(" obtain sql sentence ")
_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(" To be successful ")
}
Placeholders are also supported to build SQL.
Rows Traverse
After getting the query data , We need to traverse the data . have access to Rows Method .
stay student_service Add below TestRow Method .
The method code is as follows :
// test row Traverse the way
func (t StudentImpl) TestRow() rsp.ResponseMsg {
log.Logger.Info(" test row Traverse the way ")
_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(" perform sql abnormal ", 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(" Test success ")
}
Interface validation
controller Add interface code in layer , as follows :
// Check all student profiles
func (s StudentController) SelectOutline(context *gin.Context) {
log.Logger.Info("SelectOutline Interface ")
_rsp := services.StudentServ.SelectOutline()
context.JSON(http.StatusOK, _rsp)
}
// Use exec Update the data
func (s StudentController) UpdateExec(context *gin.Context) {
log.Logger.Info("UpdateExec Interface ")
var studentUpdateExecReq req.StudentUpdateExecReq
if err := context.ShouldBindJSON(&studentUpdateExecReq); err != nil {
log.Logger.Panic(" Parameter exception ")
}
if _, err := json.Marshal(studentUpdateExecReq); err != nil {
log.Logger.Panic(" Parameter parsing exception ")
}
_rsp := services.StudentServ.UpdateExec(studentUpdateExecReq)
context.JSON(http.StatusOK, _rsp)
}
// Query with named parameters
func (s StudentController) SelectByNamespace(context *gin.Context) {
log.Logger.Info("SelectByNamespace Interface ")
_age := context.Query("age")
_a, _ := strconv.ParseInt(_age, 10, 64)
_rsp := services.StudentServ.SelectByNamespace(int64(_a))
context.JSON(http.StatusOK, _rsp)
}
// obtain sql sentence
func (s StudentController) GetSql(context *gin.Context) {
log.Logger.Info(" obtain sql Statement interface ")
_rsp := services.StudentServ.GetSql()
context.JSON(http.StatusOK, _rsp)
}
// test row Traverse the way
func (s StudentController) TestRow(context *gin.Context) {
log.Logger.Info(" test row Traversal mode interface ")
_rsp := services.StudentServ.TestRow()
context.JSON(http.StatusOK, _rsp)
}
router Add routing path , as follows :
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)
Verify the interfaces respectively
/student/selectOutline
/student/updateExec
/student/selectByNamespace
/student/getSql
/student/testRow
Summary
Share :
All human suffering , In essence, they are angry at their own incompetence .—— Wang Xiaobo
边栏推荐
- Financial risk control practice - decision tree rule mining template
- Go 語言的 Context 詳解
- STM32 key state machine 2 - state simplification and long press function addition
- Classic questions about data storage
- PTA 天梯赛练习题集 L2-002 链表去重
- 线性回归
- Flask1.1.4 werkzeug1.0.1 source code analysis: start the process
- SQLSTATE[HY000][1130] Host ‘host. docker. internal‘ is not allowed to connect to this MySQL server
- Web authentication API compatible version information
- Value range of various datetimes in SQL Server 2008
猜你喜欢
Reading notes of Clickhouse principle analysis and Application Practice (6)
ML's shap: Based on the adult census income binary prediction data set (whether the predicted annual income exceeds 50K), use the shap decision diagram combined with the lightgbm model to realize the
一名普通学生的大一总结【不知我等是愚是狂,唯知一路向前奔驰】
Go语学习笔记 - gorm使用 - gorm处理错误 | Web框架Gin(十)
SAP ABAP BDC (batch data communication) -018
JVM the truth you need to know
JVM命令之 jinfo:实时查看和修改JVM配置参数
mac版php装xdebug环境(m1版)
关于STC单片机“假死”状态的判别
PowerPivot - DAX (function)
随机推荐
C. colonne Swapping [tri + Simulation]
Introduction to yarn (one article is enough)
关于服装ERP,你知道多少?
I didn't know it until I graduated -- the principle of HowNet duplication check and examples of weight reduction
cf:C. Column Swapping【排序 + 模擬】
【日常训练--腾讯精选50】235. 二叉搜索树的最近公共祖先
SQLSTATE[HY000][1130] Host ‘host. docker. internal‘ is not allowed to connect to this MySQL server
如何提高网站权重
CTFshow--常用姿势
Financial risk control practice - decision tree rule mining template
Harmonyos practice - Introduction to development, analysis of atomized services
软件测试面试技巧
Wechat applet Bluetooth connects hardware devices and communicates. Applet Bluetooth automatically reconnects due to abnormal distance. JS realizes CRC check bit
【FPGA教程案例13】基于vivado核的CIC滤波器设计与实现
产业金融3.0:“疏通血管”的金融科技
VScode进行代码补全
每秒10W次分词搜索,产品经理又提了一个需求!!!(收藏)
make makefile cmake qmake都是什么,有什么区别?
cf:C. Column Swapping【排序 + 模拟】
PTA 天梯赛练习题集 L2-002 链表去重