Describe the feature
gorm.DB创建出来之后也是需要关闭的。如果不关闭,程序退出时mysql会打印类似下面的日志
2022-04-10T03:27:09.414539Z 25 [Note] Aborted connection 25 to db: 'test' user: 'root' host: '172.18.0.1' (Got an error reading communication packets)
另外,如果创建gorm.DB时使用了PrepareStmt: true,如果不关闭 会导致mysql出现下面的报错:
Error 1461: Can't create more than max_prepared_stmt_count statements (current value: 5)
一般情况下这个报错很少出现,我们可以把mysql中的配置项max_prepared_stmt_count设置为max_prepared_stmt_count=5
这样,只要prepare stmt数量大于5就会出现这个这个错误
Motivation
避免mysql出现Can't create more than max_prepared_stmt_count statements这样的报错
Related Issues
Comment From: radi2015
postgresql error
failed to initialize database, got error failed to connect to host=192.168.160.12 user=xxx database=xxx: server error (FATAL: the database system is in recovery mode (SQLSTATE 57P03))
I use a pool of 10 goroutines for data processing, with a total of 200 tasks. At the same time, there will be 10 goroutines for concurrency. I do not use the connection pool, and each goroutine has a separate Gorm Open() get a db
when db *DB will be close ? this error maybe because too many connections not close
So I manually closed the connection to avoid this error db, _ := db.DB() db.Close()
Comment From: radi2015
I personally verified that if I don't manually to close, he will create a large number of connections. Gorm may close automatically later, but the database will hang up before it can be closed automatically, Is it possible that the close is too later, and the database won't wait for you to close connections. If the number of connections is too high, the database can't carry it,
Comment From: jinzhu
For prepared statement, refer https://gorm.io/docs/session.html#PrepareStmt
For normal application, in most cases, you don't need it, if you pretty sure you need it, checkout https://gorm.io/docs/generic_interface.html
GORM won't add the Close method to avoid the misusage