28 lines
610 B
Go
28 lines
610 B
Go
|
package models
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"github.com/jinzhu/gorm"
|
||
|
"log"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
var DB *gorm.DB
|
||
|
|
||
|
func Connect(host, port, dbname, username, password string) error {
|
||
|
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", username, password, host, port, dbname)
|
||
|
var err error
|
||
|
DB, err = gorm.Open("mysql", dsn)
|
||
|
if err != nil {
|
||
|
log.Println("数据库连接失败:", err)
|
||
|
//panic("数据库连接失败!")
|
||
|
return err
|
||
|
}
|
||
|
DB.SingularTable(true)
|
||
|
DB.LogMode(true)
|
||
|
DB.DB().SetMaxIdleConns(10)
|
||
|
DB.DB().SetMaxOpenConns(100)
|
||
|
DB.DB().SetConnMaxLifetime(59 * time.Second)
|
||
|
return nil
|
||
|
}
|