mysql.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package database
  2. import (
  3. "bytes"
  4. "duoduo/conf"
  5. "fmt"
  6. _ "github.com/go-sql-driver/mysql" //加载mysql
  7. "github.com/jinzhu/gorm"
  8. "log"
  9. "strconv"
  10. )
  11. var Eloquent *gorm.DB
  12. var LyMysql *gorm.DB
  13. var (
  14. Host string
  15. Port int
  16. Name string
  17. Username string
  18. Password string
  19. )
  20. func Setup() {
  21. //加载配置
  22. confIni, errConf := conf.ConnIni()
  23. if errConf != nil {
  24. fmt.Println(errConf)
  25. }
  26. Host = confIni.MustValue("mysql", "mysql_host")
  27. Port = confIni.MustInt("mysql", "mysql_port")
  28. Name = confIni.MustValue("mysql", "mysql_name")
  29. Username = confIni.MustValue("mysql", "mysql_username")
  30. Password = confIni.MustValue("mysql", "mysql_password")
  31. var err error
  32. conn := GetMysqlConnect()
  33. log.Println(conn)
  34. var db Database
  35. db = new(Mysql)
  36. Eloquent, err = db.Open("mysql", conn)
  37. if err != nil {
  38. log.Fatalf("mysql connect error %v", err)
  39. } else {
  40. log.Printf("mysql connect success!")
  41. }
  42. if Eloquent.Error != nil {
  43. log.Fatalf("database error %v", Eloquent.Error)
  44. }
  45. Eloquent.LogMode(true)
  46. //加载领养数据库链接
  47. Host = confIni.MustValue("ly-mysql", "mysql_host")
  48. Port = confIni.MustInt("ly-mysql", "mysql_port")
  49. Name = confIni.MustValue("ly-mysql", "mysql_name")
  50. Username = confIni.MustValue("ly-mysql", "mysql_username")
  51. Password = confIni.MustValue("ly-mysql", "mysql_password")
  52. conn = GetMysqlConnect()
  53. log.Println(conn)
  54. //var db Database
  55. db = new(Mysql)
  56. LyMysql, err = db.Open("mysql", conn)
  57. if err != nil {
  58. log.Fatalf("mysql connect error %v", err)
  59. } else {
  60. log.Printf("mysql connect success!")
  61. }
  62. if LyMysql.Error != nil {
  63. log.Fatalf("database error %v", Eloquent.Error)
  64. }
  65. LyMysql.LogMode(true)
  66. }
  67. func GetMysqlConnect() string {
  68. var conn bytes.Buffer
  69. conn.WriteString(Username)
  70. conn.WriteString(":")
  71. conn.WriteString(Password)
  72. conn.WriteString("@tcp(")
  73. conn.WriteString(Host)
  74. conn.WriteString(":")
  75. conn.WriteString(strconv.Itoa(Port))
  76. conn.WriteString(")")
  77. conn.WriteString("/")
  78. conn.WriteString(Name)
  79. conn.WriteString("?charset=utf8mb4&parseTime=True&loc=Local&timeout=1000ms")
  80. return conn.String()
  81. }
  82. type Database interface {
  83. Open(dbType string, conn string) (db *gorm.DB, err error)
  84. }
  85. type Mysql struct {
  86. }
  87. func (*Mysql) Open(dbType string, conn string) (db *gorm.DB, err error) {
  88. eloquent, err := gorm.Open(dbType, conn)
  89. return eloquent, err
  90. }