英文:
Golang sql database open and close
问题
在Go的database/sql包中,它说很少使用db.Close来关闭数据库,因为数据库应该被多个Go协程共享。那么当我们有100个从相同数据查询的函数时,哪种方式更好呢?
- 在每个函数内部打开数据库。
- 只打开一次数据库,并在每个函数中重复使用同一个连接。
选择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:
- Open the database inside each function
- 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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论