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

99 lines
1.9 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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. DB, dbConnErr = sql.Open("mysql", DBUSER+":"+DBPWD+"@tcp("+DBHOST+":"+DBPORT+")/"+DBNAME+"?charset=utf8")
  18. if dbConnErr != nil {
  19. log.Println("ERROR", "can not connect to Database, ", dbConnErr)
  20. time.Sleep(time.Second * 5)
  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, dbtype ...string) string {
  50. var db_type string = "mysql"
  51. if len(dbtype) > 0 {
  52. if dbtype[0] != "" {
  53. db_type = dbtype[0]
  54. }
  55. }
  56. var ret string
  57. switch db_type {
  58. case "mysql":
  59. if strings.Contains(table, ".") {
  60. ret = table
  61. }
  62. if dbName != "" {
  63. ret = helper.StringJoin(dbName, ".", table)
  64. } else {
  65. ret = table
  66. }
  67. case "mssql":
  68. ret = helper.StringJoin(dbName, ".", table)
  69. }
  70. return ret
  71. }
  72. func GetDbTableName(dbName, table string) string {
  73. return getTableName(dbName, table)
  74. }
  75. func judg() []string {
  76. return []string{"=", ">", "<", "!=", "<=", ">="}
  77. }