package dbquery import ( "database/sql" "errors" "fmt" "strconv" "log" "time" _ "github.com/denisenkom/go-mssqldb" ) var MSDB_CONN *sql.DB func MSConnect(DBHOST, DBUSER, DBPWD, DBNAME, DBPORT string, conns ...int) error { log.Println("msdb connectting...") var dbConnErr error if DBHOST != "" && DBUSER != "" && DBPWD != "" && DBPORT != "" { //&& DBNAME != "" for i := 0; i < 10; i++ { //连接字符串 db_port, _ := strconv.Atoi(DBPORT) connString := fmt.Sprintf("server=%s;port=%d;database=%s;user id=%s;password=%s", DBHOST, db_port, DBNAME, DBUSER, DBPWD) log.Println(connString) //建立连接 MSDB_CONN, dbConnErr = sql.Open("mssql", connString) if dbConnErr != nil { log.Println("ERROR", "can not connect to Database, ", dbConnErr) time.Sleep(time.Second * 5) } else { err = MSDB_CONN.Ping() log.Println("msdb connected", err) break } } } else { return errors.New("msdb connection params errors") } return dbConnErr } func CloseMSConn() error { if MSDB_CONN != nil { return MSDB_CONN.Close() } return nil }