在Go中关闭应用程序之前是否需要关闭数据库连接?

In Go, when using a SQL database, does one need to close the DB (db.Close) before closing an application? Will the DB automatically detect that the connection has died?

DB will do its best to detect but with no luck, it may not be able to detect. Better to release what is acquired as soon as possible.

send() system call will wait for TCP connection to send data but client won't receive anything.

  1. Power failure, network issue or bare exit happened without properly releasing resources. TCP keepalive mechanism will kick in and try to detect that connection is dead.

  2. Client is paused and doesn't receive any data, in this case send() will block.

As a result, it may prevent

  1. Graceful shutdown of cluster.
  2. Advancing event horizon if it was holding exclusive locks as a part of transaction such as auto vacuum in postgresql.

Server keepalive config could be shortened to detect it earlier. (For example, ~2h 12m default in postgresql will be very long according to workload).

There may be a hard limit on max open connections, until detection, some connections will be zombie (there, unusable but decreases limit).

It is good practice to release any resource which was utilized. What DB are you utilizing.

If you're initialising a connection in any function, you're normally better off deferring the call to close immediately, i.e.

conn := sql.Connect() // for example
defer conn.Close()

Which will close the connection once the enclosing function exits.

This is handy when used in a main function since once the program exits, the call to Close() will happen.

The database will notice the connection had died and take appropriate actions: for instance, all uncommitted transactions active on that connection will be rolled back and the user session will be terminated.

But notice that this is a "recovery" scenario from the point of view of the database engine: it cannot just throw up when a client disconnects; it rather have to take explicit actions to have consistent state.

On the other hand, to shut down property when the program goes down "the normal way" (that is, not because of a panic or log.Fatal()) is really not that hard. And since the sql.DB instance is usually a program-wide global variable, its even simpler: just try closing it in main() like Matt suggested.