-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql.go
54 lines (43 loc) · 953 Bytes
/
mysql.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
package util
import (
"database/sql"
"fmt"
// mysql
_ "github.com/go-sql-driver/mysql"
)
var Mysqldb *sql.DB
const (
// DefaultDataBase 默认数据库
DefaultDataBase = "dc_mind"
connectCount = 3
)
// InitMysql 初始化mysql连接池
func InitMysql() error {
datasourceName := mysqlDataSourceName(
cfg.Mysql.Host,
cfg.Mysql.User,
cfg.Mysql.Password,
cfg.Mysql.Port,
DefaultDataBase)
var err error
for i := 0; i < connectCount; i++ {
Mysqldb, err = sql.Open("mysql", datasourceName)
if err != nil {
Logger.Error("mysql connect fail:" + datasourceName)
}
Mysqldb.SetMaxOpenConns(100)
Mysqldb.SetMaxIdleConns(100)
Mysqldb.Ping()
}
return err
}
// MysqlDataSourceName 返回mysql的连接字符串
func mysqlDataSourceName(host string, user string, password string, port int, dbName string) string {
return fmt.Sprintf(
"%s:%s@tcp(%s:%d)/%s?charset=utf8",
user,
password,
host,
port,
dbName)
}