在包之间共享 SQL 连接的惯用方式是什么?

huangapple go评论118阅读模式
英文:

What is the idiomatic way to share an SQL connection between packages?

问题

通常我会在主包中声明一个公共的Db变量。

  1. package main
  2. var Db *sql.DB
  3. func main() {
  4. var err error
  5. Db, err = sql.Open("sqlite3", BARS_FILE)
  6. if err != nil {
  7. log.Fatal(err)
  8. }
  9. defer Db.Close()
  10. // 将Db作为参数传递给其他包中的函数(数据库存储库)
  11. }

有没有更好的方法来做这个?

英文:

I usually declare a public Db variable in the main package

  1. package main
  2. var Db *sql.DB
  3. func main() {
  4. var err error
  5. Db, err = sql.Open("sqlite3", BARS_FILE)
  6. if err != nil {
  7. log.Fatal(err)
  8. }
  9. defer Db.Close()
  10. // passing Db as a parameter to other functions in other packages (database
  11. // repositories)
  12. }

Is there a better way of doing this?

答案1

得分: 2

根据http://golang.org/pkg/database/sql/#DB的说明,可以安全地使用sql.DB:

DB是一个数据库句柄。它可以被多个goroutine并发使用。

在我看来,这种用法是可以的。也许以后,当这个变量成为瓶颈时,你可以创建更多的句柄。如果有很多goroutine开始使用它,这种情况可能会发生。但在必要之前不要进行优化。

英文:

According to http://golang.org/pkg/database/sql/#DB it is safe to use sql.DB this way:

> DB is a database handle. It's safe for concurrent use by multiple
> goroutines.

And IMHO it is ok to use it that way. Maybe later, when this variable becomes bottleneck you could create more handles. It could happen if a lot of gouroutines start using it. But do not optimize before it is necessary.

huangapple
  • 本文由 发表于 2014年4月12日 00:15:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/23017688.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定