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

相关文章

SQL中的外键约束

外键约束用于表示两张表中的指标连接关系。外键约束的作用主要有以下三点: 1.确保子表中的某个字段(外键)只能引用父表中的有效记录2.主表中的列被删除时,子表中的关联列也会被删除3.主表中的列更新时,子表中的关联元素也会被更新 子表中的元素指向主表 以下是一个外键约束的实例展示

基于MySQL Binlog的Elasticsearch数据同步实践

一、为什么要做 随着马蜂窝的逐渐发展,我们的业务数据越来越多,单纯使用 MySQL 已经不能满足我们的数据查询需求,例如对于商品、订单等数据的多维度检索。 使用 Elasticsearch 存储业务数据可以很好的解决我们业务中的搜索需求。而数据进行异构存储后,随之而来的就是数据同步的问题。 二、现有方法及问题 对于数据同步,我们目前的解决方案是建立数据中间表。把需要检索的业务数据,统一放到一张M

如何去写一手好SQL

MySQL性能 最大数据量 抛开数据量和并发数,谈性能都是耍流氓。MySQL没有限制单表最大记录数,它取决于操作系统对文件大小的限制。 《阿里巴巴Java开发手册》提出单表行数超过500万行或者单表容量超过2GB,才推荐分库分表。性能由综合因素决定,抛开业务复杂度,影响程度依次是硬件配置、MySQL配置、数据表设计、索引优化。500万这个值仅供参考,并非铁律。 博主曾经操作过超过4亿行数据

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

性能分析之MySQL索引实战案例

文章目录 一、前言二、准备三、MySQL索引优化四、MySQL 索引知识回顾五、总结 一、前言 在上一讲性能工具之 JProfiler 简单登录案例分析实战中已经发现SQL没有建立索引问题,本文将一起从代码层去分析为什么没有建立索引? 开源ERP项目地址:https://gitee.com/jishenghua/JSH_ERP 二、准备 打开IDEA找到登录请求资源路径位置

MySQL数据库宕机,启动不起来,教你一招搞定!

作者介绍:老苏,10余年DBA工作运维经验,擅长Oracle、MySQL、PG、Mongodb数据库运维(如安装迁移,性能优化、故障应急处理等)公众号:老苏畅谈运维欢迎关注本人公众号,更多精彩与您分享。 MySQL数据库宕机,数据页损坏问题,启动不起来,该如何排查和解决,本文将为你说明具体的排查过程。 查看MySQL error日志 查看 MySQL error日志,排查哪个表(表空间

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo