連線資料庫

GORM 正式支援 MySQL、PostgreSQL、SQLite、SQL Server 和 TiDB 等資料庫

MySQL

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

func main() {
// refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
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 Driver 提供 一些進階設定,可以在初始化期間使用,例如

db, err := gorm.Open(mysql.New(mysql.Config{
DSN: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local", // data source name
DefaultStringSize: 256, // default size for string fields
DisableDatetimePrecision: true, // disable datetime precision, which not supported before MySQL 5.6
DontSupportRenameIndex: true, // drop & create when rename index, rename index not supported before MySQL 5.7, MariaDB
DontSupportRenameColumn: true, // `change` when rename column, rename column not supported before MySQL 8, MariaDB
SkipInitializeWithVersion: false, // auto configure based on currently MySQL version
}), &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, refer 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 驅動程式,它預設啟用已準備好的陳述式快取,若要停用它

// 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{})

SQLite

import (
"gorm.io/driver/sqlite" // Sqlite driver based on CGO
// "github.com/glebarez/sqlite" // Pure go SQLite driver, checkout https://github.com/glebarez/sqlite for details
"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()" 標籤來使用 AUTO_RANDOM 功能。
  • TiDB 從 v6.2.0 開始支援 SAVEPOINT,請在使用此功能時注意 TiDB 的版本。
  • TiDB 從 v6.6.0 開始支援 FOREIGN KEY,請在使用此功能時注意 TiDB 的版本。
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, Price: %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, Price: %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 := "tcp://127.0.0.1:9000?database=gorm&username=gorm&password=gorm&read_timeout=10&write_timeout=20"
db, err := gorm.Open(clickhouse.Open(dsn), &gorm.Config{})

// Auto Migrate
db.AutoMigrate(&User{})
// Set table options
db.Set("gorm:table_options", "ENGINE=Distributed(cluster, default, hits)").AutoMigrate(&User{})

// Insert
db.Create(&user)

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

// Batch Insert
var users = []User{user1, user2, user3}
db.Create(&users)
// ...
}

連線池

GORM 使用 database/sql 來維護連線池

sqlDB, err := db.DB()

// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
sqlDB.SetMaxIdleConns(10)

// SetMaxOpenConns sets the maximum number of open connections to the database.
sqlDB.SetMaxOpenConns(100)

// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
sqlDB.SetConnMaxLifetime(time.Hour)

有關詳細資訊,請參閱 通用介面

不支援的資料庫

有些資料庫可能與 mysqlpostgres 方言相容,在這種情況下,您只需使用這些資料庫的方言即可。

對於其他資料庫,我們鼓勵您製作驅動程式,歡迎提交請求!

白金贊助商

金牌贊助商

白金贊助商

金牌贊助商