db.go 593 B

123456789101112131415161718192021222324252627
  1. package db
  2. import (
  3. "fmt"
  4. _ "github.com/go-sql-driver/mysql"
  5. "github.com/jmoiron/sqlx"
  6. )
  7. type Config struct {
  8. UserName string
  9. Password string
  10. Ip string
  11. Port int
  12. DbName string
  13. Charset string
  14. }
  15. // 连接数据库
  16. func ConnectMysql(conf *Config) *sqlx.DB {
  17. dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", conf.UserName, conf.Password, conf.Ip, conf.Port, conf.DbName, conf.Charset)
  18. Db, err := sqlx.Open("mysql", dsn)
  19. if err != nil {
  20. fmt.Printf("mysql connect failed, detail is [%v]", err.Error())
  21. }
  22. return Db
  23. }