12345678910111213141516171819202122232425262728 |
- package databases
- import (
- "database/sql"
- "fmt"
- _ "github.com/go-sql-driver/mysql"
- "ydMonitoring/config"
- )
- var Db *sql.DB
- func init() {
- host := config.Config.GetString("datasource.host")
- port := config.Config.GetString("datasource.port")
- dbname := config.Config.GetString("datasource.dbname")
- username := config.Config.GetString("datasource.username")
- password := config.Config.GetString("datasource.password")
- var datasource string = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", username, password, host, port, dbname)
- db, err := sql.Open("mysql", datasource)
- if err != nil {
- panic(any("初始化数据库失败,请检查数据库配置是否正确!"))
- }
- _, err = db.Exec("show tables")
- if err != nil {
- panic(any("数据库连接失败,请检查!" + err.Error()))
- }
- Db = db
- }
|