mysql.go 791 B

12345678910111213141516171819202122232425262728
  1. package databases
  2. import (
  3. "database/sql"
  4. "fmt"
  5. _ "github.com/go-sql-driver/mysql"
  6. "useEquipmentTimeEarlyWARNING/config"
  7. )
  8. var Db *sql.DB
  9. func init() {
  10. host := config.Config.GetString("datasource.host")
  11. port := config.Config.GetString("datasource.port")
  12. dbname := config.Config.GetString("datasource.dbname")
  13. username := config.Config.GetString("datasource.username")
  14. password := config.Config.GetString("datasource.password")
  15. var datasource string = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", username, password, host, port, dbname)
  16. db, err := sql.Open("mysql", datasource)
  17. if err != nil {
  18. panic("初始化数据库失败,请检查数据库配置是否正确!")
  19. }
  20. _, err = db.Exec("show tables")
  21. if err != nil {
  22. panic("数据库连接失败,请检查!")
  23. }
  24. Db = db
  25. }