mysqlpool.go 661 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package mysqlpool
  2. import (
  3. "database/sql"
  4. "sync"
  5. )
  6. type MySqlPool struct {
  7. sync.RWMutex
  8. connections map[string]*sql.DB
  9. }
  10. func New() *MySqlPool {
  11. r := MySqlPool{}
  12. r.connections = map[string]*sql.DB{}
  13. return &r
  14. }
  15. func (this *MySqlPool) Get(key string) *sql.DB {
  16. this.Lock()
  17. defer this.Unlock()
  18. if value, ok := this.connections[key]; ok == true {
  19. return value
  20. }
  21. return nil
  22. }
  23. func (this *MySqlPool) Set(key string, value *sql.DB) {
  24. this.Lock()
  25. defer this.Unlock()
  26. this.connections[key] = value
  27. }
  28. func (this *MySqlPool) CloseAll() {
  29. this.Lock()
  30. defer this.Unlock()
  31. for _, c := range this.connections {
  32. if c != nil {
  33. c.Close()
  34. }
  35. }
  36. }