一、介绍
database/sql 采纳策略模式,每个 driver 实现驱动,提供一个注册连接词。
var (
driversMu sync.RWMutex
drivers = make(map[string]driver.Driver)
)
// Register makes a database driver available by the provided name.
// If Register is called twice with the same name or if driver is nil,
// it panics.
func Register(name string, driver driver.Driver) {driversMu.Lock()
defer driversMu.Unlock()
if driver == nil {panic("sql: Register driver is nil")
}
if _, dup := drivers[name]; dup {panic("sql: Register called twice for driver" + name)
}
drivers[name] = driver
}
当咱们应用不同的数据库的时候,只有把应用的驱动注册进去就能够了。
比方在 github.com/go-sql-driver/mysql mysql 驱动库里。
有一段代码
github.com/go-sql-driver/mysql/driver.go
func init() {sql.Register("mysql", &MySQLDriver{})
}
这里注册是在 drivers 的 map 的一个 key,关联一个 driver。