连接到数据库

GORM officially supports the databases MySQL, PostgreSQL, GaussDB, SQLite, SQL Server TiDB, and Oracle Database

MySQL

import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)

func main() {
// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
}

**注意:**想要正确的处理 time.Time ,您需要带上 parseTime 参数, (更多参数) 要支持完整的 UTF-8 编码,您需要将 charset=utf8 更改为 charset=utf8mb4 查看 此文章 获取详情

MySQL 驱动程序提供了 一些高级配置 可以在初始化过程中使用,例如:

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

自定义驱动

GORM 允许通过 DriverName 选项自定义 MySQL 驱动,例如:

import (
_ "example.com/my_mysql_driver"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)

db, err := gorm.Open(mysql.New(mysql.Config{
DriverName: "my_mysql_driver",
DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local", // data source name, 详情参考:https://github.com/go-sql-driver/mysql#dsn-data-source-name
}), &gorm.Config{})

现有的数据库连接

GORM 允许通过一个现有的数据库连接来初始化 *gorm.DB

import (
"database/sql"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)

sqlDB, err := sql.Open("mysql", "mydb_dsn")
gormDB, err := gorm.Open(mysql.New(mysql.Config{
Conn: sqlDB,
}), &gorm.Config{})

PostgreSQL

import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
)

dsn := "host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

我们使用 pgx 作为 postgres 的 database/sql 驱动,默认情况下,它会启用 prepared statement 缓存,你可以这样禁用它:

// https://github.com/go-gorm/postgres
db, err := gorm.Open(postgres.New(postgres.Config{
DSN: "user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai",
PreferSimpleProtocol: true, // disables implicit prepared statement usage
}), &gorm.Config{})

自定义驱动

GORM 允许通过 DriverName 选项自定义 PostgreSQL 驱动,例如:

import (
_ "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/postgres"
"gorm.io/gorm"
)

db, err := gorm.Open(postgres.New(postgres.Config{
DriverName: "cloudsqlpostgres",
DSN: "host=project:region:instance user=postgres dbname=postgres password=password sslmode=disable",
})

现有的数据库连接

GORM 允许通过一个现有的数据库连接来初始化 *gorm.DB

import (
"database/sql"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)

sqlDB, err := sql.Open("pgx", "mydb_dsn")
gormDB, err := gorm.Open(postgres.New(postgres.Config{
Conn: sqlDB,
}), &gorm.Config{})

GaussDB

import (
"gorm.io/driver/gaussdb"
"gorm.io/gorm"
)

dsn := "host=localhost user=gorm password=gorm dbname=gorm port=8000 sslmode=disable TimeZone=Asia/Shanghai"
db, err := = gorm. Open(gaussdb.Open(dsn), &gorm.Config{})

我们正在使用 gaussdb-go 作为gaussdb’s database/sql 驱动器,它默认允许准备好的语句缓存以禁用它:

// https://github.com/go-gorm/gaussdb
db, err := gorm.Open(gaussdb.New(gaussdb.Config{
DSN: "user=gorm password=gorm dbname=gorm port=8000 sslmode=disable TimeZone=Asia/Shanghai",
PreferSimpleProtocol: true, // 禁用隐式 prepared statement
}), &gorm.Config{})

自定义驱动程序

GORM 允许使用 DriverName 自定义GaussDB 驱动程序,例如:

import (
_ "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialars/gaussdb"
"gorm.io/gorm"
)

db, err := gorm. Open(gaussdb.Newsdb. onfig@un.org
DriverName: "cloudsqlgaussdb",
DSN: "host=project:region:instance user=gaussdb dbname=gaussdb password=password=disable",
})

现有数据库连接

GORM 允许使用现有数据库连接初始化 *gorm.DB

import (
"database/sql"
"gorm.io/driver/gaussdb"
"gorm.io/gorm"
)

sqlDB, err := sql. pen("gaussdbgo", "mydb_dsn")
gormDB, err := gorm.Open(gaussdb.New(gaussdb.Config
Conn: sqlDB,
}), &gorm.Config{})

Oracle Database

The GORM Driver for Oracle provides support for Oracle Database, enabling full compatibility with GORM’s ORM capabilities. It is built on top of the Go Driver for Oracle (Godror) and supports key features such as auto migrations, associations, transactions, and advanced querying.

Prerequisite: Install Instant Client

To use ODPI-C with Godror, you’ll need to install the Oracle Instant Client on your system. Follow the steps on this page to complete the installation.

After that, you can connect to the database using the dataSourceName, which specifies connection parameters (such as username and password) using a logfmt-encoded parameter list.

The way you specify the Instant Client directory differs by platform:

  • macOS and Windows: You can set the libDir parameter in the dataSourceName.
  • Linux: The libraries must be in the system library search path before your Go process starts, preferably configured with “ldconfig”. The libDir parameter does not work on Linux.

Example (macOS/Windows)

dataSourceName := `user="scott" password="tiger" 
connectString="dbhost:1521/orclpdb1"
libDir="/Path/to/your/instantclient_23_26"`

Example (Linux)

dataSourceName := `user="scott" password="tiger" 
connectString="dbhost:1521/orclpdb1"`

Getting Started

import (
"github.com/oracle-samples/gorm-oracle/oracle"
"gorm.io/gorm"
)

dataSourceName := `user="scott" password="tiger"
connectString="dbhost:1521/orclpdb1"`
db, err := gorm.Open(oracle.Open(dataSourceName), &gorm.Config{})

SQLite

import (
"gorm.io/driver/sqlite" // 基于 CGO 的 Sqlite 驱动
// "github.com/glebarez/sqlite" // 纯 Go 实现的 SQLite 驱动, 详情参考:https://github.com/glebarez/sqlite
"gorm.io/gorm"
)

// github.com/mattn/go-sqlite3
db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})

注意: 您也可以使用 file::memory:?cache=shared 替代文件路径。 这会告诉 SQLite 在系统内存中使用一个临时数据库。 (查看 SQLite 文档 获取详情)

SQL Server

import (
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
)

// github.com/denisenkom/go-mssqldb
dsn := "sqlserver://gorm:LoremIpsum86@localhost:9930?database=gorm"
db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{})

TiDB

TiDB 兼容 MySQL 协议。 因此你可以按照 MySQL 一节来创建与 TiDB 的连接。

在使用 TiDB 时有一些值得注意的内容:

  • 您可以在结构体中使用 gorm:"primaryKey;default:auto_random()" 标签从而调用 TiDB 的 AUTO_RANDOM 功能。
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)

type Product struct {
ID uint `gorm:"primaryKey;default:auto_random()"`
Code string
Price uint
}

func main() {
db, err := gorm.Open(mysql.Open("root:@tcp(127.0.0.1:4000)/test"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}

db.AutoMigrate(&Product{})

insertProduct := &Product{Code: "D42", Price: 100}

db.Create(insertProduct)
fmt.Printf("insert ID: %d, Code: %s, Prict: %d\n",
insertProduct.ID, insertProduct.Code, insertProduct.Price)

readProduct := &Product{}
db.First(&readProduct, "code = ?", "D42") // find product with code D42

fmt.Printf("read ID: %d, Code: %s, Prict: %d\n",
readProduct.ID, readProduct.Code, readProduct.Price)
}

Clickhouse

https://github.com/go-gorm/clickhouse

import (
"gorm.io/driver/clickhouse"
"gorm.io/gorm"
)

func main() {
dsn := "clickhouse://gorm:gorm@localhost:9942/gorm?dial_timeout=10s&read_timeout=20s"
db, err := gorm.Open(clickhouse.Open(dsn), &gorm.Config{})

// 自动迁移 (这是GORM自动创建表的一种方式--译者注)
db.AutoMigrate(&User{})
// 设置表选项
db.Set("gorm:table_options", "ENGINE=Distributed(cluster, default, hits)").AutoMigrate(&User{})

// 插入
db.Create(&user)

// 查询
db.Find(&user, "id = ?", 10)

// 批量插入
var users = []User{user1, user2, user3}
db.Create(&users)
// ...
}

连接池

GORM 使用 database/sql 来维护连接池

sqlDB, err := db.DB()

// SetMaxIdleConns 设置空闲连接池中连接的最大数量。
sqlDB.SetMaxIdleConns(10)

// SetMaxOpenConns 设置打开数据库连接的最大数量。
sqlDB.SetMaxOpenConns(100)

// SetConnMaxLifetime 设置了可以重新使用连接的最大时间。
sqlDB.SetConnMaxLifetime(time.Hour)

查看 通用接口 获取详情。

还未支持的数据库

有些数据库可能兼容 mysqlpostgres 的方言,在这种情况下,你可以直接使用这些数据库的方言。

对于其他还未支持的数据库驱动,我们鼓励开发者积极的提交更多类型的数据库驱动!

Platinum Sponsors

Become a Sponsor!

Platinum Sponsors

Become a Sponsor!