Skip to content

初始化方法MySQL

Tuuz edited this page Oct 27, 2023 · 2 revisions

同时你可以参考TuuzGoWeb中database的方法,编写自己的初始化方式

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/tobycroft/gorose-pro"
)

var Database *gorose.Engin


func dsn() string {
    dbname := "gorose"
    dbuser := "gorose"
    dbpass := "123456"
    dbhost := "192.168.1.1"
    conntype := "tcp"
    dbport := "3306"
    charset := "utf8mb4"
    return dbuser + ":" + dbpass + "@" + conntype + "(" + dbhost + ":" + dbport + ")/" + dbname + "?charset=" + charset + "&parseTime=true"
}

func DbConfig() *gorose.Config {
    var conf gorose.Config
    conf.Driver = "mysql"
    conf.SetMaxIdleConns = 90
    conf.SetMaxOpenConns = 300
    conf.Prefix = ""
    conf.Dsn = dsn()
    return &conf
}

func init() {
    var err error
    Database, err = gorose.Open(DbConfig())
    if err != nil {
        log.Panic(err)
    }
}

//注意这个db就是后续文档中调用的初始化db方法
func DB() gorose.IOrm {
    return database.Database.NewOrm()
}