gin结合gorm实现mysql增删改查

2024-03-12 19:38

本文主要是介绍gin结合gorm实现mysql增删改查,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

https://gin-gonic.com/

https://gorm.io/zh_CN/docs/index.html

https://github.com/gin-gonic/gin/

https://github.com/go-gorm/gorm

集成

go mod方式

require (github.com/gin-contrib/sessions v0.0.3github.com/gin-gonic/gin v1.6.2github.com/go-sql-driver/mysql v1.5.0gorm.io/driver/mysql v1.0.3gorm.io/gorm v1.20.5
)

链接mysql

package coreimport ("gorm.io/driver/mysql""gorm.io/gorm"
)func Connection() (*gorm.DB) {dsn := "root:123456@tcp(127.0.0.1:3306)/goblog?charset=utf8&parseTime=True&loc=Local"db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})if err !=  nil {panic(err)}return db
}

 

使用

model

package modelstype Post struct {ID         int64 CategoryId int64 `form:"category_id"`Title      string `form:"title"`Image      string `form:"image"`Content    string `form:"content"`Sort       int `form:"sort"`Status     int `form:"status"`CreatedAt  int64UpdatedAt  int64
}

增删改查

package logicsimport ("myweb/app/models"
)func ListPost(datas []models.Post, page int) ([]models.Post, int64, error) {var pageSize = 2offset := (page - 1) * pageSizeresult := db.Order("id desc").Offset(offset).Limit(pageSize).Find(&datas)return datas, result.RowsAffected, result.Error
}func CreatePost(data models.Post) (int64, error) {result := db.Create(&data) return data.ID, result.Error
}func FindPost(id int64) (models.Post, error) {var model models.Postresult := db.First(&model, id)return model, result.Error
}func UpdatePost(data models.Post, id int64) (int64, error) {var model models.Postrow := db.First(&model, id)if row.Error == nil {result := db.Model(&model).Updates(&data)return model.ID, result.Error}return 0, row.Error
}func DeletePost(id int64) (int64, error) {var model models.Postresult := db.Delete(&model, id)return result.RowsAffected, result.Error
}

 

congroller

package controllersimport ("github.com/gin-gonic/gin""net/http""myweb/app/logics""myweb/app/models""myweb/app/utils""strconv""path"
)func ListPost(c *gin.Context) {page, _ := strconv.Atoi(c.Query("page"))if page == 0 {page = 1}var list []models.Postres, rows, err := logics.ListPost(list, page)if err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=文章错误&href=/home&err=" + err.Error())}c.HTML(http.StatusOK, "post_list.html", gin.H{"title": "文章列表", "list": res, "pageTotal": rows})
}func NewPost(c *gin.Context) {var list []models.Categorycategories, err := logics.ListCategory(list)if err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=分类错误&href=/home&err=" + err.Error())}c.HTML(http.StatusOK, "post_new.html", gin.H{"title": "新增文章", "categories": categories})
}func CreatePost(c *gin.Context) {var model models.Postfile, err := c.FormFile("file")if err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=请选择文件&href=/posts/new&err=" + err.Error())}if err := c.Bind(&model); err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=新增文章错误&href=/posts/new&err=" + err.Error())}if file != nil {// 获取后缀fileSuffix := path.Ext(file.Filename)// 新文件名称newFileName := utils.GetRoundName(12) + fileSuffix// 创建保存文件夹saveDir := utils.GetSaveDir("app/static/upload")SaveFile := saveDir + "/" + newFileNamec.SaveUploadedFile(file, SaveFile)model.Image = SaveFile}if _, err := logics.CreatePost(model); err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=新增文章错误&href=/posts/new&err=" + err.Error())}c.Redirect(http.StatusMovedPermanently, "/posts")
}func EditPost(c *gin.Context) {id, _ := strconv.ParseInt(c.Param("id"), 10, 64)res, err := logics.FindPost(id)if err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=获取文章错误&href=/posts&err=" + err.Error())}var list []models.Categorycategories, err := logics.ListCategory(list)if err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=分类错误&href=/home&err=" + err.Error())}c.HTML(http.StatusOK, "post_edit.html", gin.H{"title": "修改文章", "id": id, "model": res, "categories": categories})
}func UpdatePost(c *gin.Context) {id, _ := strconv.ParseInt(c.Param("id"), 10, 64)var model models.Postfile, err := c.FormFile("file")if err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=请选择文件&href=/posts/new&err=" + err.Error())}if file != nil {// 获取后缀fileSuffix := path.Ext(file.Filename)// 新文件名称newFileName := utils.GetRoundName(12) + fileSuffix// 创建保存文件夹saveDir := utils.GetSaveDir("app/static/upload")SaveFile := saveDir + "/" + newFileNamec.SaveUploadedFile(file, SaveFile)model.Image = SaveFile}if err := c.Bind(&model); err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=更新文章错误&href=/posts/edit/"+ strconv.FormatInt(id,10) +"&err=" + err.Error())}if _, err := logics.UpdatePost(model, id); err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=更新文章错误&href=/posts/edit/"+ strconv.FormatInt(id,10) +"&err=" + err.Error())}c.Redirect(http.StatusMovedPermanently, "/posts")return
}func DeletePost(c *gin.Context) {id, _ := strconv.ParseInt(c.Param("id"), 10, 64)if _, err := logics.DeletePost(id); err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=删除文章错误&href=/posts&err=" + err.Error())}c.Redirect(http.StatusMovedPermanently, "/posts")return
}

 

路由

package routersimport ("github.com/gin-gonic/gin""myweb/app/controllers"
)func InitRouter() *gin.Engine {router := gin.Default()router.Static("/static", "app/static")router.LoadHTMLGlob("app/templates/*")router.GET("/error",controllers.ErrorPage)router.GET("/categories",controllers.ListCategory)router.GET("/categories/new",controllers.NewCategory)router.POST("/categories/create",controllers.CreateCategory)router.GET("/categories/edit/:id",controllers.EditCategory)router.POST("/categories/update/:id",controllers.UpdateCategory)router.GET("/categories/delete/:id",controllers.DeleteCategory)router.GET("/posts",controllers.ListPost)router.GET("/posts/new",controllers.NewPost)router.POST("/posts/create",controllers.CreatePost)router.GET("/posts/edit/:id",controllers.EditPost)router.POST("/posts/update/:id",controllers.UpdatePost)router.GET("/posts/delete/:id",controllers.DeletePost)return router}

 

列表页面

{{ range .list }}<tr><td>{{ .ID }}</td><td>{{ .Title }}</td><td>{{ .Sort }}</td><td>{{ .UpdatedAt }}</td><td><a class="layui-btn layui-btn-xs" lay-event="edit" href="/posts/edit/{{ .ID }}">编辑</a> <a class="layui-btn layui-btn-danger layui-btn-xs" href="/posts/delete/{{ .ID }}">删除</a></td></tr>{{end}}

 

入口

package mainimport ("myweb/app/core""myweb/app/routers"
)func main() {core.Connection()router := routers.InitRouter()//静态资源router.Run(":8081")
}

 

 

项目地址: https://github.com/tang05709/gin-learn

这篇关于gin结合gorm实现mysql增删改查的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/802362

相关文章

nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析(结合应用场景)

《nginx-t、nginx-sstop和nginx-sreload命令的详细解析(结合应用场景)》本文解析Nginx的-t、-sstop、-sreload命令,分别用于配置语法检... 以下是关于 nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析,结合实际应

SQL server数据库如何下载和安装

《SQLserver数据库如何下载和安装》本文指导如何下载安装SQLServer2022评估版及SSMS工具,涵盖安装配置、连接字符串设置、C#连接数据库方法和安全注意事项,如混合验证、参数化查... 目录第一步:打开官网下载对应文件第二步:程序安装配置第三部:安装工具SQL Server Manageme

C#连接SQL server数据库命令的基本步骤

《C#连接SQLserver数据库命令的基本步骤》文章讲解了连接SQLServer数据库的步骤,包括引入命名空间、构建连接字符串、使用SqlConnection和SqlCommand执行SQL操作,... 目录建议配合使用:如何下载和安装SQL server数据库-CSDN博客1. 引入必要的命名空间2.

全面掌握 SQL 中的 DATEDIFF函数及用法最佳实践

《全面掌握SQL中的DATEDIFF函数及用法最佳实践》本文解析DATEDIFF在不同数据库中的差异,强调其边界计算原理,探讨应用场景及陷阱,推荐根据需求选择TIMESTAMPDIFF或inte... 目录1. 核心概念:DATEDIFF 究竟在计算什么?2. 主流数据库中的 DATEDIFF 实现2.1

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

MySQL 多列 IN 查询之语法、性能与实战技巧(最新整理)

《MySQL多列IN查询之语法、性能与实战技巧(最新整理)》本文详解MySQL多列IN查询,对比传统OR写法,强调其简洁高效,适合批量匹配复合键,通过联合索引、分批次优化提升性能,兼容多种数据库... 目录一、基础语法:多列 IN 的两种写法1. 直接值列表2. 子查询二、对比传统 OR 的写法三、性能分析

Linux下删除乱码文件和目录的实现方式

《Linux下删除乱码文件和目录的实现方式》:本文主要介绍Linux下删除乱码文件和目录的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux下删除乱码文件和目录方法1方法2总结Linux下删除乱码文件和目录方法1使用ls -i命令找到文件或目录

MySQL中的LENGTH()函数用法详解与实例分析

《MySQL中的LENGTH()函数用法详解与实例分析》MySQLLENGTH()函数用于计算字符串的字节长度,区别于CHAR_LENGTH()的字符长度,适用于多字节字符集(如UTF-8)的数据验证... 目录1. LENGTH()函数的基本语法2. LENGTH()函数的返回值2.1 示例1:计算字符串

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推