/
mysql_data_pool.go
56 lines (51 loc) · 1.37 KB
/
mysql_data_pool.go
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package static
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type MysqlDataPool struct {
db *gorm.DB
}
// InitMysql
//
// @Description: 通过参数初始化数据库
// @receiver d
// @param host
// @param port
// @param username
// @param password
// @param dbName
func (d *MysqlDataPool) InitMysql(host string, port string, username string, password string, dbName string) {
var err error
url := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True", username, password, host, port, dbName)
fmt.Println("init mysql with " + url)
d.db, err = gorm.Open(mysql.Open(url), &gorm.Config{})
if err != nil {
fmt.Println("could not init db " + err.Error())
panic("db error")
}
}
// InitMysqlWithConfig
//
// @Description: 通过配置初始化数据库
// @receiver d
// @param config
func (d *MysqlDataPool) InitMysqlWithConfig(config map[string]string) {
var err error
url := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True", config["username"], config["password"], config["host"], config["port"], config["database"])
fmt.Println("init mysql with " + url)
d.db, err = gorm.Open(mysql.Open(url), &gorm.Config{})
if err != nil {
fmt.Println("could not init db " + err.Error())
panic("db error")
}
}
// GetDB
//
// @Description: 获取数据库连接
// @receiver d
// @return *gorm.DB
func (d *MysqlDataPool) GetDB() *gorm.DB {
return d.db
}