当前位置: 首页 > 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                    stringServerVersion                 stringDSN                           stringDSNConfig                     *mysql.ConfigConn                          gorm.ConnPoolSkipInitializeWithVersion     boolDefaultStringSize             uintDefaultDatetimePrecision      *intDisableWithReturning          boolDisableDatetimePrecision      boolDontSupportRenameIndex        boolDontSupportRenameColumn       boolDontSupportForShareClause     boolDontSupportNullAsDefaultValue boolDontSupportRenameColumnUnique 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.htmlDontSupportDropConstraint 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 trueSkipDefaultTransaction    boolDefaultTransactionTimeout time.DurationDefaultContextTimeout     time.Duration// NamingStrategy tables, columns naming strategyNamingStrategy schema.Namer// FullSaveAssociations full save associationsFullSaveAssociations bool// LoggerLogger logger.Interface// NowFunc the function to be used when creating a new timestampNowFunc func() time.Time// DryRun generate sql without executeDryRun bool// PrepareStmt executes the given query in cached statementPrepareStmt bool// PrepareStmt cache support LRU expired,// default maxsize=int64 Max value and ttl=1hPrepareStmtMaxSize intPrepareStmtTTL     time.Duration// DisableAutomaticPingDisableAutomaticPing bool// DisableForeignKeyConstraintWhenMigratingDisableForeignKeyConstraintWhenMigrating bool// IgnoreRelationshipsWhenMigratingIgnoreRelationshipsWhenMigrating bool// DisableNestedTransaction disable nested transactionDisableNestedTransaction bool// AllowGlobalUpdate allow global updateAllowGlobalUpdate bool// QueryFields executes the SQL query with all fields of the tableQueryFields bool// CreateBatchSize default create batch sizeCreateBatchSize int// TranslateError enabling error translationTranslateError bool// PropagateUnscoped propagate Unscoped to every other nested statementPropagateUnscoped bool// ClauseBuilders clause builderClauseBuilders map[string]clause.ClauseBuilder// ConnPool db conn poolConnPool ConnPool// Dialector database dialectorDialector// Plugins registered pluginsPlugins map[string]Plugincallbacks  *callbackscacheStore *sync.Map
}

数据库代码编写

package daoimport ("fmt""gorm.io/driver/mysql""gorm.io/gorm/logger""gorm.io/gorm"
)var _db *gorm.DBfunc 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 = linkDBif 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

💕👉博客专栏

  • SpringCloud微服务-从Spring出发学习从0学习微服务!

  • Golang专栏-包含基础、Gin、Goam等知识

  • 云原生专栏-包含k8s、docker等知识

  • 从0开始学习云计算-华为HCIP证书

  • JUC专栏-带你快速领悟JUC的知识!

  • JVM专栏-深入Java虚拟机,理解JVM的原理

  • 基于Java研究 数据结构与算法-包含贪心算法、加权图、最短路径算法等知识

  • Docker专栏-上手热门容器技术Docker

  • SpringBoot专栏-学习SpringBoot快速开发后端

  • 项目管理工具的学习-设计技术:Maven、Git、Gradle等相关管理工具

  • JavaSE-全面了解Java基础

  • JS专栏-使用JS作的一部分实例~

  • 使用CSS所作的一部分案例

http://www.dtcms.com/a/585195.html

相关文章:

  • AIStarter 服务器版 PanelAI 开源+早鸟票 抢商业永久授权
  • 【项目】pyqt5基于python的照片整蛊项目
  • 深入理解Java堆栈:从原理到面试实战
  • MySQL快速入门——基本查询(下)
  • PyTorch深度学习进阶(二)(批量归一化)
  • 基于字符串的专项实验
  • CPO-SVM回归 基于冠豪猪优化算法支持向量机的多变量回归预测 (多输入单输出)Matlab
  • 飞凌嵌入式ElfBoard-标准IO接口之关闭文件
  • Rust 练习册 :Prime Factors与质因数分解
  • 12380网站开发apache wordpress rewrite
  • CSS - transition 过渡属性及使用方法(示例代码)
  • web网页开发,在线%考试管理%系统,基于Idea,vscode,html,css,vue,java,maven,springboot,mysql
  • 2025年北京海淀区中小学生信息学竞赛第一赛段试题(附答案)
  • Linux 基础开发工具入门:软件包管理器的全方位实操指南
  • 金仓数据库用户权限隔离:从功能兼容到安全增强的技术演进
  • shell(4)--shell脚本中的循环:(if循环,for,while,until)和退出循环(continue,break, exit)
  • IDEA 软件下载 + 安装 | 操作步骤
  • seo建站推广泉州建站软件
  • HarmonyOS 诗词填空游戏开发实战教程(非AI生成 提供源代码和演示视频)
  • 【期末网页设计作业】HTML+CSS+JavaScript 蜡笔小新 动漫主题网站设计与实现(附源码)
  • 柳州建站衣联网和一起做网站。哪家强
  • 深入解析CFS虚拟运行时间:Linux公平调度的核心引擎
  • cdr做网站流程哪家公司做网站结算好
  • 专业课复习计划
  • SQL50+Hot100系列(11.8)
  • 猫狗识别数据集:34,441张高质量标注图像,深度学习二分类任务训练数据集,计算机视觉算法研发,CNN模型训练,图像识别分类,机器学习实践项目完整数据资
  • DOM NodeList 简介
  • 【数据结构】unordered 系列容器底层结构和封装
  • 昆明做网站要多少钱京津冀协同发展交通一体化规划
  • Rust编程学习 - 问号运算符会return一个Result 类型,但是如何使用main函数中使用问号运算符