Golang打开和关闭SQL数据库。

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

Golang sql database open and close

问题

在Go的database/sql包中,它说很少使用db.Close来关闭数据库,因为数据库应该被多个Go协程共享。那么当我们有100个从相同数据查询的函数时,哪种方式更好呢?

  1. 在每个函数内部打开数据库。
  2. 只打开一次数据库,并在每个函数中重复使用同一个连接。

选择1更容易,因为如果一个函数失败,其他99个函数仍然可以正常工作。而且不需要传递数据库连接参数。但从性能方面来看,哪种方式更好呢?

英文:

In Go database/sql package it says it is rare to close the database with db.Close because it is meant to be shared by many go routines. Then which one is better when we are given 100 functions that queries from a same data:

  1. Open the database inside each function
  2. Open the database only one time and use the same connection for every 100 function.

1 is easier because if one fails other 99 can still be working. And no need to pass database connection arguments. But in performance wise which one is better?

答案1

得分: 11

你错过了文档中的一个重要部分:

> 返回的DB对象可以安全地供多个goroutine并发使用,并且维护自己的空闲连接池。因此,应该只调用一次Open函数。很少需要关闭DB。

(我强调的部分)

所以,你的第二个选项实际上没有意义。连接是被池化的,所以“对于每100个函数使用相同的连接”不适用。此外,选项1是浪费时间的 - 只需按照文档中的说明执行一次,但在执行后调用Ping以确保一切正常(并实际尝试连接到数据库 - 无论驱动程序如何)。

英文:

You missed an important part of what the documentation says:

> The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.

(emphasis mine)

So, your option #2 doesn't actually make sense. The connections are pooled - so use the same connection for every 100 function doesn't apply. Also, option #1 is a waste of time - just do it once as the documentation states, but call Ping after you do just to make sure everything is fine (and have it actually attempt to connect to the database - regardless of driver).

huangapple
  • 本文由 发表于 2014年12月2日 11:03:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/27241187.html
匿名

发表评论

匿名网友

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

确定