当前位置:   article > 正文

Golang Gin框架搭建项目(四)gorm/mysql_gin基础框架 包含mysqgorm

gin基础框架 包含mysqgorm

1、安装包:

  1. go get -u gorm.io/gorm
  2. go get -u gorm.io/driver/mysql

2、帮助类MySqlUtil:

  1. package utils
  2. import (
  3. "fmt"
  4. "gin_demo/config"
  5. "gorm.io/driver/mysql"
  6. "gorm.io/gorm"
  7. "gorm.io/gorm/logger"
  8. "strconv"
  9. )
  10. type mySqlUtil struct {
  11. DB *gorm.DB
  12. }
  13. //全局变量, 外部使用utils.MySqlClient来访问
  14. var MySqlClient mySqlUtil
  15. func InitMySqlUtil(config config.DatabaseConfig) error {
  16. dsn := buildDatabaseDSN(config)
  17. fmt.Println(dsn)
  18. dd, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
  19. Logger: logger.Default.LogMode(logger.Warn),
  20. })
  21. if err != nil {
  22. panic("[SetupDefaultDatabase#newConnection error]: " + err.Error() + " " + dsn)
  23. }
  24. sqlDB, err := dd.DB()
  25. if err != nil {
  26. panic("[SetupDefaultDatabase#newConnection error]: " + err.Error() + " " + dsn)
  27. }
  28. if config.MaxOpenConns > 0 {
  29. sqlDB.SetMaxOpenConns(config.MaxOpenConns)
  30. }
  31. if config.MaxIdleConns > 0 {
  32. sqlDB.SetMaxIdleConns(config.MaxIdleConns)
  33. }
  34. fmt.Printf("\nDefault atabase connection successful: %s\n", dsn)
  35. //初始化全局redis结构体
  36. MySqlClient = mySqlUtil{DB: dd}
  37. return nil
  38. }
  39. func buildDatabaseDSN(config config.DatabaseConfig) string {
  40. switch config.Driver {
  41. case "mysql":
  42. return fmt.Sprintf(
  43. "%s:%s@tcp(%s:%s)/%s?%s",
  44. config.User,
  45. config.Password,
  46. config.Host,
  47. strconv.Itoa(config.Port),
  48. config.DbName,
  49. config.Options,
  50. )
  51. case "postgres":
  52. return fmt.Sprintf(
  53. "host=%s port=%s user=%s dbname=%s password=%s options='%s'",
  54. config.Host,
  55. strconv.Itoa(config.Port),
  56. config.User,
  57. config.DbName,
  58. config.Password,
  59. config.Options,
  60. )
  61. case "sqlite3":
  62. return config.DbName
  63. case "mssql":
  64. return fmt.Sprintf(
  65. "sqlserver://%s:%s@%s:%s?database=%s&%s",
  66. config.User,
  67. config.Password,
  68. config.Host,
  69. strconv.Itoa(config.Port),
  70. config.DbName,
  71. config.Options,
  72. )
  73. }
  74. panic("DB Connection not supported:" + config.Driver)
  75. return ""
  76. }

3、定义一个含有基础增删改查的类,其它数据库操作类都继承这个:

  1. package dao
  2. import (
  3. "errors"
  4. "fmt"
  5. "gin_demo/utils"
  6. )
  7. type BaseDao struct {
  8. }
  9. //新增
  10. func (BaseDao) Add(model interface{}) (err error) {
  11. err = utils.MySqlClient.DB.Create(model).Error
  12. return
  13. }
  14. //根据Id查询
  15. func (BaseDao) Get(model interface{}, id int) error {
  16. fmt.Println("UserInfoDao Get")
  17. if id < 1 {
  18. return errors.New("请输入id")
  19. }
  20. _ = utils.MySqlClient.DB.First(&model, id)
  21. return nil
  22. }
  23. //更新
  24. func (BaseDao) UpdateModel(value interface{}) (err error) {
  25. err = utils.MySqlClient.DB.Save(value).Error
  26. return
  27. }
  28. //删除
  29. func (BaseDao) DeleteModel(value interface{}) (err error) {
  30. err = utils.MySqlClient.DB.Delete(value).Error
  31. return
  32. }

4、用户相关的增删改查,继承BaseDao:UserInfoDao

  1. package dao
  2. import (
  3. "gin_demo/models"
  4. "gin_demo/utils"
  5. )
  6. type UserInfoDao struct {
  7. BaseDao
  8. }
  9. var UserInfo = UserInfoDao{}
  10. //修改用户名
  11. func (UserInfoDao) UpdateUserName(name string, id int) error {
  12. err := utils.MySqlClient.DB.Model(&models.UserInfo{}).Where("id = ?", id).Update("name", name).Error
  13. return err
  14. }
  15. //分页查询用户列表
  16. func (UserInfoDao) GetUserPageList(index int, size int) ([]models.UserInfo, error) {
  17. results := make([]models.UserInfo, 0)
  18. err := utils.MySqlClient.DB.Model(&models.UserInfo{}).Where("age < ?", 20).Where("name LIKE ?", "%王").Limit(size).Offset(index * size).Find(&results).Error
  19. return results, err
  20. }
  1. package models
  2. //数据库表结构
  3. type UserInfo struct {
  4. Id int `gorm:"primaryKey;autoIncrement" form:"id"`
  5. Name string `form:"name"`
  6. Age int `form:"age"`
  7. }
  8. // 自定义表名
  9. func (UserInfo) TableName() string {
  10. return "userinfo"
  11. }

 

5、main.go初始化数据库:

  1. package main
  2. import (
  3. "gin_demo/config"
  4. "gin_demo/routers"
  5. "gin_demo/utils"
  6. "github.com/gin-gonic/gin"
  7. )
  8. func main() {
  9. conf, err := config.ParseConfig("./config/app.json")
  10. if err != nil {
  11. panic("读取配置文件失败," + err.Error())
  12. }
  13. //fmt.Printf("conf:%#v\n", conf)
  14. utils.InitRedisUtil(conf.RedisConfig.Addr, conf.RedisConfig.Port, conf.RedisConfig.Password)
  15. utils.InitMySqlUtil(conf.Database)
  16. //创建一个默认的路由引擎
  17. engine := gin.Default()
  18. routers.RegisterRouter(engine)
  19. engine.Run(":9090")
  20. }

6、使用:

  1. package controller
  2. import (
  3. "gin_demo/config"
  4. "gin_demo/dao"
  5. "gin_demo/models"
  6. "github.com/gin-gonic/gin"
  7. "net/http"
  8. "strconv"
  9. )
  10. type UserController struct {
  11. }
  12. //新增用户
  13. func (controller *UserController) Add(context *gin.Context) {
  14. //name := context.PostForm("name")
  15. var user models.UserInfo
  16. err := context.ShouldBindJSON(&user)
  17. if err != nil {
  18. context.JSON(http.StatusOK, gin.H{"msg": "参数错误"})
  19. return
  20. }
  21. dao.UserInfo.Add(&user)
  22. context.JSON(http.StatusOK, gin.H{"user": user})
  23. }
  24. //查询用户
  25. func (controller *UserController) Get(context *gin.Context) {
  26. id, _ := strconv.Atoi(context.Query("id"))
  27. println("id:", id)
  28. var user models.UserInfo
  29. dao.UserInfo.Get(&user, id)
  30. context.JSON(http.StatusOK, gin.H{
  31. "id": id,
  32. "conf": config.GetConfig(),
  33. "user": user,
  34. //"hello": hello,
  35. })
  36. }
  37. //分页查询
  38. func (controller *UserController) GetPageList(context *gin.Context) {
  39. index, _ := strconv.Atoi(context.Query("index"))
  40. println("index:", index)
  41. size, _ := strconv.Atoi(context.Query("size"))
  42. println("size:", size)
  43. list, _ := dao.UserInfo.GetUserPageList(index, size)
  44. context.JSON(http.StatusOK, gin.H{
  45. "users": list,
  46. })
  47. }
  48. //分页查询
  49. func (controller *UserController) UpdateUserName(context *gin.Context) {
  50. name := context.PostForm("name")
  51. println("name:", name)
  52. id, _ := strconv.Atoi(context.PostForm("id"))
  53. println("id:", id)
  54. _ = dao.UserInfo.UpdateUserName(name, id)
  55. context.JSON(http.StatusOK, gin.H{
  56. "code": 1,
  57. })
  58. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/1021989
推荐阅读
相关标签
  

闽ICP备14008679号