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

79 lines
1.6 KiB

3 years ago
  1. package dbquery
  2. import (
  3. "database/sql"
  4. "log"
  5. "errors"
  6. "strings"
  7. "time"
  8. "git.tetele.net/tgo/helper"
  9. _ "github.com/go-sql-driver/mysql"
  10. )
  11. var DB *sql.DB
  12. func Connect(DBHOST, DBUSER, DBPWD, DBNAME, DBPORT string, conns ...int) error {
  13. log.Println("database connectting...")
  14. var dbConnErr error
  15. if DBHOST != "" && DBUSER != "" && DBPWD != "" && DBPORT != "" { //&& DBNAME != ""
  16. for i := 0; i < 10; i++ {
  17. time.Sleep(time.Second * 5)
  18. DB, dbConnErr = sql.Open("mysql", DBUSER+":"+DBPWD+"@tcp("+DBHOST+":"+DBPORT+")/"+DBNAME+"?charset=utf8")
  19. if dbConnErr != nil {
  20. log.Println("ERROR", "can not connect to Database, ", dbConnErr)
  21. } else {
  22. if len(conns) > 0 {
  23. DB.SetMaxOpenConns(conns[0]) //用于设置最大打开的连接数,默认值为0表示不限制
  24. } else {
  25. DB.SetMaxOpenConns(200) //默认值为0表示不限制
  26. }
  27. if len(conns) > 1 {
  28. DB.SetMaxIdleConns(conns[1]) //用于设置闲置的连接数
  29. } else {
  30. DB.SetMaxIdleConns(50)
  31. }
  32. DB.Ping()
  33. log.Println("database connected")
  34. DB.SetConnMaxLifetime(time.Minute * 2)
  35. break
  36. }
  37. }
  38. } else {
  39. return errors.New("db connection params errors")
  40. }
  41. return dbConnErr
  42. }
  43. func CloseConn() error {
  44. return DB.Close()
  45. }
  46. /**
  47. * 检测表名
  48. */
  49. func getTableName(dbName, table string) string {
  50. if strings.Contains(table, ".") {
  51. return table
  52. }
  53. if dbName != "" {
  54. return helper.StringJoin(dbName, ".", table)
  55. } else {
  56. return table
  57. }
  58. }
  59. func GetDbTableName(dbName, table string) string {
  60. return getTableName(dbName, table)
  61. }
  62. func judg() []string {
  63. return []string{"=", ">", "<", "!=", "<=", ">="}
  64. }