数据库操作
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.1 KiB

3 years ago
  1. package dbquery
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "strconv"
  7. "log"
  8. "time"
  9. _ "github.com/denisenkom/go-mssqldb"
  10. )
  11. var MSDB_CONN *sql.DB
  12. func MSConnect(DBHOST, DBUSER, DBPWD, DBNAME, DBPORT string, conns ...int) error {
  13. log.Println("msdb connectting...")
  14. var dbConnErr error
  15. if DBHOST != "" && DBUSER != "" && DBPWD != "" && DBPORT != "" { //&& DBNAME != ""
  16. for i := 0; i < 10; i++ {
  17. //连接字符串
  18. db_port, _ := strconv.Atoi(DBPORT)
  19. connString := fmt.Sprintf("server=%s;port=%d;database=%s;user id=%s;password=%s", DBHOST, db_port, DBNAME, DBUSER, DBPWD)
  20. log.Println(connString)
  21. //建立连接
  22. MSDB_CONN, dbConnErr = sql.Open("mssql", connString)
  23. if dbConnErr != nil {
  24. log.Println("ERROR", "can not connect to Database, ", dbConnErr)
  25. time.Sleep(time.Second * 5)
  26. } else {
  27. err = MSDB_CONN.Ping()
  28. log.Println("msdb connected", err)
  29. break
  30. }
  31. }
  32. } else {
  33. return errors.New("msdb connection params errors")
  34. }
  35. return dbConnErr
  36. }
  37. func CloseMSConn() error {
  38. if MSDB_CONN != nil {
  39. return MSDB_CONN.Close()
  40. }
  41. return nil
  42. }