GORM 官方支持的數(shù)據(jù)庫類型有: MySQL,PostgreSQL,SQlite,SQL Server
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{})
}
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{})
import (
"gorm.io/driver/sqlite" // Sqlite driver based on GGO
// "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{})
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{})
GORM 使用database/sql維護(hù)連接池
sqlDB, err := db.DB()
// SetMaxIdleConns 設(shè)置空閑連接池中連接的最大數(shù)量
sqlDB.SetMaxIdleConns(10)
// SetMaxOpenConns 設(shè)置打開數(shù)據(jù)庫連接的最大數(shù)量。
sqlDB.SetMaxOpenConns(100)
// SetConnMaxLifetime 設(shè)置了連接可復(fù)用的最大時間。
sqlDB.SetConnMaxLifetime(time.Hour)
更多建議: