mysql.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package orm
  2. import (
  3. "fmt"
  4. "gorm.io/driver/mysql"
  5. "gorm.io/gorm"
  6. )
  7. type MysqlConfig struct {
  8. Dns string
  9. MaxIdleConns int
  10. MaxOpenConns int
  11. }
  12. func NewMysql(mysqlConf *MysqlConfig) *gorm.DB {
  13. db, err := gorm.Open(mysql.New(mysql.Config{
  14. DSN: mysqlConf.Dns, // DSN data source name
  15. DefaultStringSize: 256, // string 类型字段的默认长度
  16. //DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
  17. //DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
  18. //DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
  19. //SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置
  20. }), &gorm.Config{
  21. DisableForeignKeyConstraintWhenMigrating: true,
  22. })
  23. if err != nil {
  24. fmt.Println(err)
  25. }
  26. sqlDB, err2 := db.DB()
  27. if err2 != nil {
  28. fmt.Println(err2)
  29. }
  30. // SetMaxIdleConns 设置空闲连接池中连接的最大数量
  31. sqlDB.SetMaxIdleConns(mysqlConf.MaxIdleConns)
  32. // SetMaxOpenConns 设置打开数据库连接的最大数量。
  33. sqlDB.SetMaxOpenConns(mysqlConf.MaxOpenConns)
  34. return db
  35. }