1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- // Copyright 2019 github.com. All rights reserved.
- // Use of this source code is governed by github.com.
- package databasev1
- import (
- "fmt"
- "log"
- "github.com/jinzhu/gorm"
- _ "github.com/jinzhu/gorm/dialects/mysql"
- )
- var db *gorm.DB
- // Setup 建立连接
- func Setup(user, passwd, addr, dbname, charset string, maxIdle, maxConn int, logMode bool) *gorm.DB {
- // 组装参数
- args := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&parseTime=True&loc=Local",
- user, passwd, addr, dbname, charset)
- // 打开新连接
- var err error
- db, err = gorm.Open("mysql", args)
- if err != nil {
- log.Fatal("open mysql connection failed. err: ", err)
- }
- // 其他设置
- db.LogMode(logMode)
- db.DB().SetMaxIdleConns(maxIdle)
- db.DB().SetMaxOpenConns(maxConn)
- return db
- }
- // DB 获取连接
- func DB() *gorm.DB {
- return db
- }
- // Close 关闭连接
- func Close() {
- if db != nil {
- db.Close()
- }
- }
|