mysql - 有正确的方法连接到MySQL吗?

标签 mysql go

我遇到过的文档说:

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()

在需要使用它的函数中调用了该函数,据我所知,这将打开连接,然后在到达该函数末尾时将其关闭。

这会违反上面的引用吗?

最佳答案

该示例编写得很糟糕,是的,除非它们的数据存储区不同,否则您不应该OpenClose
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/

相关文章:

go - Go 中的接收器(方法)放在哪里?

azure - 如何从Azure应用配置中读取值

php - 从数组中检索数据

mysql - 在 MySQL 数据库中存储纬度/经度时使用的理想数据类型是什么?

php - 错误消息不适用于 PHP 用户检查

android - 在 appengine 或 android 上,我在哪里可以获得应用内计费 v3 api 的 token ?

sql - 列出每年最多产的三位作者

php - 分解并在行中搜索

golang windows服务失败,没有任何错误

go - 从 redis 中获取所有 key