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

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

MySQL

  1. package main
  2. import (
  3. "fmt"
  4. "gorm.io/driver/mysql"
  5. "gorm.io/gorm"
  6. )
  7. func main() {
  8. // 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
  9. dsn := "root:root_pwd@tcp(192.168.66.100:3306)/gorm_class?charset=utf8mb4&parseTime=True&loc=Local"
  10. db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
  11. if err != nil {
  12. fmt.Printf("err: %v\n", err)
  13. }
  14. fmt.Println(db, err)
  15. }

正常成功h话运行返回

  1. &{0xc00020e240 <nil> 0 0xc00022e000 1} <nil>

注意:想要正确的处理 time.Time ,您需要带上 parseTime 参数, (更多参数) 要支持完整的 UTF-8 编码,您需要将 charset=utf8 更改为 charset=utf8mb4 查看 此文章 获取详情
MySQl 驱动程序提供了 一些高级配置 可以在初始化过程中使用,例如:

  1. db, err := gorm.Open(mysql.New(mysql.Config{
  2. DSN: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local", // DSN data source name
  3. DefaultStringSize: 256, // string 类型字段的默认长度
  4. DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
  5. DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
  6. DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
  7. SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置
  8. }), &gorm.Config{})


内容来自
https://gorm.cn/zh_CN/docs/connecting_to_the_database.html