数据库操作
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.

70 lines
1.2 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, encrypt 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. params := "server=%s;port=%d;database=%s;user id=%s;password=%s"
  20. if encrypt != "" {
  21. params = params + ";encrypt=" + encrypt
  22. }
  23. connString := fmt.Sprintf(params, DBHOST, db_port, DBNAME, DBUSER, DBPWD)
  24. log.Println(connString)
  25. //建立连接
  26. MSDB_CONN, dbConnErr = sql.Open("mssql", connString)
  27. if dbConnErr != nil {
  28. log.Println("ERROR", "can not connect to Database, ", dbConnErr)
  29. time.Sleep(time.Second * 5)
  30. } else {
  31. err = MSDB_CONN.Ping()
  32. log.Println("msdb connected", err)
  33. break
  34. }
  35. }
  36. } else {
  37. return errors.New("msdb connection params errors")
  38. }
  39. return dbConnErr
  40. }
  41. func CloseMSConn() error {
  42. if MSDB_CONN != nil {
  43. return MSDB_CONN.Close()
  44. }
  45. return nil
  46. }