我遇到过的文档说:
the sql.DB object is designed to be long-lived. Don’t Open() and Close() databases frequently. Instead, create one sql.DB object for each distinct datastore you need to access
source
并四处寻找,我通常会找到在处理程序文件中打开连接的代码
func dbConn() (db *sql.DB) {
dbDriver := "mysql"
dbUser := "root"
dbPass := "root"
dbName := "goblog"
db, err := sql.Open(dbDriver, dbUser+":"+dbPass+"@/"+dbName)
if err != nil {
panic(err.Error())
}
return db
}
source
并访问数据库
db := dbConn()
在需要使用它的函数中调用了该函数,据我所知,这将打开连接,然后在到达该函数末尾时将其关闭。
这会违反上面的引用吗?
最佳答案
该示例编写得很糟糕,是的,除非它们的数据存储区不同,否则您不应该Open
和Close
。Open
返回DB
和
DB is a database handle representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines
关于mysql - 有正确的方法连接到MySQL吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59782604/