mysql.go 943 B

12345678910111213141516171819202122232425262728293031323334
  1. package clinit
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "github.com/astaxie/beego/orm"
  7. )
  8. type MysqlConfig struct {
  9. User string `json:"user"`
  10. Password string `json:"password"`
  11. Addr string `json:"addr"`
  12. DB string `json:"db"`
  13. Charset string `json:"charset"`
  14. MaxIdle json.Number `json:"max_idle"`
  15. MaxConn json.Number `json:"max_conn"`
  16. }
  17. func InitMySQL(conf *MysqlConfig) {
  18. dataSource := fmt.Sprintf(`%s:%s@tcp(%s)/%s?charset=%s`, conf.User, conf.Password, conf.Addr, conf.DB, conf.Charset)
  19. if err := orm.RegisterDriver("mysql", orm.DRMySQL); err != nil {
  20. fmt.Printf("register mysql driver failed. error:%s\n", err)
  21. os.Exit(1)
  22. }
  23. maxIdle, _ := conf.MaxIdle.Int64()
  24. maxConn, _ := conf.MaxConn.Int64()
  25. if err := orm.RegisterDataBase("default", "mysql", dataSource, int(maxIdle), int(maxConn)); err != nil {
  26. fmt.Printf("register mysql data base failed. error:%s", err)
  27. os.Exit(1)
  28. }
  29. }