1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
package main
import (
"database/sql"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"time"
)
func main() {
// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
dsn := "root:root@tcp(127.0.0.1:3306)/go_db?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
fmt.Println("连接失败")
}
sqlDB, err := db.DB()
// 方法结束后执行,关闭连接池
defer func(sqlDB *sql.DB) {
err := sqlDB.Close()
if err != nil {
fmt.Println("关闭失败")
}
}(sqlDB) // 关闭链接
// 设置连接池参数
sqlDB.SetMaxIdleConns(10) // SetMaxIdleConns 设置空闲连接池中的最大连接数
sqlDB.SetMaxOpenConns(100) // SetMaxOpenConns 设置数据库的最大打开连接数
sqlDB.SetConnMaxLifetime(time.Hour) // SetConnMaxLifetime 设置连接可重用的最大时间量
}
|