你应该在不再需要连接数据库的时候关闭sql.DB。

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

Where should I close the sql.DB?

问题

根据godoc的说明:

> 很少需要关闭DB,因为DB句柄应该是长期存在的,可以在多个goroutine之间共享。

除了在main函数中使用defer db.Close()之外,还有其他用例吗?

英文:

According to the godoc:

> It is rare to Close a DB, as the DB handle is meant to be long-lived
> and shared between many goroutines.

Is there any use cases of this method except calling it defer db.Close() inside the main function?

答案1

得分: 1

我从不关闭数据库。在主函数中推迟关闭数据库可能不会有什么问题...但也不会有任何帮助。主函数的结束意味着程序的结束,如果主函数结束,操作系统会进行清理。

编辑:
如果你不打算再次使用数据库,关闭数据库是有用的。它会执行在程序终止时进行的所有清理工作,但允许程序继续运行。

英文:

I never close databases. Deferring it in main likely won't hurt... but it won't help anything either. The end of main is the end of the program and if main ends, the OS does the cleaning.


Edit:

> So why we need it in public API of the database/sql package?

Closing a DB is useful if you don't plan to use the database again. It does all the cleanup that would be done at program termination but allows the program to continue to run.

huangapple
  • 本文由 发表于 2014年9月16日 07:54:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/25858663.html
匿名

发表评论

匿名网友

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

确定