当前位置: 首页 > news >正文

【GORM(3)】Go的跨时代ORM框架!—— 数据库连接、配置参数;本文从0开始教会如何配备GORM的数据库

数据库连接

GORM官方支持的数据库类型有:MySQL、PostgreSQL、SQlite、SQL Server

连接数据库主要时两个步骤:

  1. 配置DSN
  2. 使用gorm.Open连接数据库

DSN(Data Source Name)

gorm库使用dsn作为连接数据库的参数,dsn翻译:数据源名称;

其主要目的是用来描述数据库连接信息。

一般包含:

看看案例中的DSN格式:

username := "root"   // 用户名
password := "123456" // 密码
host := "localhost"
port := "3306"
DbName := "go_test"
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", username, password, host, port, DbName)

?后面就是连接数据库的配置参数,使用&来定义多个参数

参数说明注意
charset编码字符集建议utf8mb4,支持更广泛的字符
parseTime时间类型转换必加,支持数据库datetimedate类型转为go的time.Time类型
loc时区默认Local,必加
timeout超时时间定义尝试连接的时间,超出定义的时长后报错
readTimeout读超时时间0表示不限制
writeTimeout写超时时间0表示不限制

连接数据库

import(
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main(){
dsn:="username:password@tcp(localhost:3306)/dbname?charset=utf8mb4&parseTime&loc=Local"
db,err := gorm.Open(mysql.Open(dsn),&gorm.Config{})
}

GORM支持自定义配置Mysql的配置信息

db, err := gorm.Open(mysql.New(mysql.Config{
DSN:                      dsn,
DefaultStringSize:        191,
DisableDatetimePrecision: true,
}), &gorm.Config{})

mysql.New(mysql.Config{})使用这个就可以了,mysql.Config结构体内部定义了很多mysql的配置参数;

type Config struct {
DriverName                    string
ServerVersion                 string
DSN                           string
DSNConfig                     *mysql.Config
Conn                          gorm.ConnPool
SkipInitializeWithVersion     bool
DefaultStringSize             uint
DefaultDatetimePrecision      *int
DisableWithReturning          bool
DisableDatetimePrecision      bool
DontSupportRenameIndex        bool
DontSupportRenameColumn       bool
DontSupportForShareClause     bool
DontSupportNullAsDefaultValue bool
DontSupportRenameColumnUnique bool
// As of MySQL 8.0.19, ALTER TABLE permits more general (and SQL standard) syntax
// for dropping and altering existing constraints of any type.
// see https://dev.mysql.com/doc/refman/8.0/en/alter-table.html
DontSupportDropConstraint bool
}

针对连接池,Gorm也给出了设置方式,只需通过db进行设置即可

_db, err := db.DB()
if err != nil {
panic(err)
}
_db.SetMaxIdleConns(10)
_db.SetMaxOpenConns(100)

当我们设置了gorm的配置打印时,我们可以看到每一条日志信息;而我们不想要所有的日志都打印出来,可以使用调试模式

res := DB.Debug().Model(&Good{}).Where("id=?", id).First(&data)

在发送SQL语句的go代码行中添加Debug()函数即可

func (db *DB) Debug() (tx *DB) {
tx = db.getInstance()
return tx.Session(&Session{
Logger: db.Logger.LogMode(logger.Info),
})
}

函数内部也只是定义了日志模式

若在连接数据库时定义,会是全局的打印

db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})

既然Mysql可以配置连接池,Gorm同样也不止可以设置日志打印的参数,gorm.Config内部还定义了其他的参数

// Config GORM config
type Config struct {
// GORM perform single create, update, delete operations in transactions by default to ensure database data integrity
// You can disable it by setting `SkipDefaultTransaction` to true
SkipDefaultTransaction    bool
DefaultTransactionTimeout time.Duration
DefaultContextTimeout     time.Duration
// NamingStrategy tables, columns naming strategy
NamingStrategy schema.Namer
// FullSaveAssociations full save associations
FullSaveAssociations bool
// Logger
Logger logger.Interface
// NowFunc the function to be used when creating a new timestamp
NowFunc func() time.Time
// DryRun generate sql without execute
DryRun bool
// PrepareStmt executes the given query in cached statement
PrepareStmt bool
// PrepareStmt cache support LRU expired,
// default maxsize=int64 Max value and ttl=1h
PrepareStmtMaxSize int
PrepareStmtTTL     time.Duration
// DisableAutomaticPing
DisableAutomaticPing bool
// DisableForeignKeyConstraintWhenMigrating
DisableForeignKeyConstraintWhenMigrating bool
// IgnoreRelationshipsWhenMigrating
IgnoreRelationshipsWhenMigrating bool
// DisableNestedTransaction disable nested transaction
DisableNestedTransaction bool
// AllowGlobalUpdate allow global update
AllowGlobalUpdate bool
// QueryFields executes the SQL query with all fields of the table
QueryFields bool
// CreateBatchSize default create batch size
CreateBatchSize int
// TranslateError enabling error translation
TranslateError bool
// PropagateUnscoped propagate Unscoped to every other nested statement
PropagateUnscoped bool
// ClauseBuilders clause builder
ClauseBuilders map[string]clause.ClauseBuilder
// ConnPool db conn pool
ConnPool ConnPool
// Dialector database dialector
Dialector
// Plugins registered plugins
Plugins map[string]Plugin
callbacks  *callbacks
cacheStore *sync.Map
}

数据库代码编写

package dao
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm/logger"
"gorm.io/gorm"
)
var _db *gorm.DB
func init() {
username := "root"   // 用户名
password := "123456" // 密码
host := "localhost"
port := "3306"
DbName := "go_test"
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", username, password, host, port, DbName)
linkDB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
db, err := linkDB.DB()
if err != nil {
panic(err)
}
db.SetMaxIdleConns(10)
db.SetMaxOpenConns(100)
_db = linkDB
if err != nil {
panic("failed to connect database, err: " + err.Error())
}
}
func getDB() *gorm.DB {
if _db == nil {
return nil
}
return _db
}

使用gorm内部的连接的DB,还是需要通过_db来设置私有变量,再通过方法获取会更好

GORM 专栏前瞻回顾

  1. 【GORM(1)】Go的跨时代ORM框架!本文带你入门GORM! - 目录结构分析、基本CRUD(增删改查)代码直接复制粘贴即可运行!
  2. 【GORM(2)】Go的跨时代ORM框架!本文带你入门GORM!—— 映射模型与表名映射;GORM与JSON对应的标签详情说明;提供数据库SQL

博客专栏

http://www.jsqmd.com/news/84134/

相关文章:

  • 2025年12月苏州装修品牌调研:盛世和家装饰的三大核心优势解析 - 品牌测评鉴赏家
  • ~给媳妇的新称呼~
  • 含GABA的睡眠益生菌品牌哪家靠谱?多款热门品牌解析 - 品牌排行榜
  • 图书管理系统 (C语言 + 数据库功能)
  • 用你的生日,取一个微信昵称
  • 2025年12月苏州装修品牌调研:盛世和家装饰的售后服务深度解析 - 品牌测评鉴赏家
  • 2025年12月苏州装修品牌调研:盛世和家装饰——行业寒冬中的本土标杆优势解码 - 品牌测评鉴赏家
  • 代码随想录34_动态规划2
  • Rust 实战:手把手教你实现高性能快速排序
  • 通达信222222测试帖别下载
  • 【健康管理】第13章 医学伦理与职业道德
  • Zig 语言实战:实现高性能快速排序算法
  • 通达信大盘个股共振指标公式
  • VIPCalendar-全球节假日日历工具,支持打印与ICS导入
  • 通达信老鹰抓鱼主图指标公式
  • java计算机毕业设计社区服务微信小程序 基于微信生态的社区便民服务平台 SpringBoot+微信小程智慧社区服务系统
  • 代码随想录33_动态规划2
  • STM32F407驱动3.5寸ILI9486屏幕
  • 暂停更新975年,这神器值得拥有!
  • 这些核心特征,让芯片散料转编带设备成行业刚需
  • FIFO学习笔记--访问同步/异步 读写同步/异步
  • 25、技术探索:从数据查询到包管理的全面指南
  • Python内置函数:你以为你很熟,但这些用法90%的人不知道
  • 高端酒店设计公司推荐:行业优质服务提供商盘点 - 品牌排行榜
  • 453453
  • 27、Python 包管理工具全解析
  • 羞耻!被秀了1脸!
  • 2025小学生兴趣班指南:5大核心维度+TOP5机构测评家长选班不踩坑 - 品牌测评鉴赏家
  • 公司禅道笔记(一):公网服务器centos6上成功部署禅道20.8版本 - 指南
  • 543567