简体   繁体   中英

Where should I close the sql.DB?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM