This is a created article in which the information may have evolved or changed.
Be careful #golang# the pitfalls in the official documentation that are not described in detail
Recently in high load when using Golang SQL driver encountered leakage problem, finally found Database/sql document and Examples are not very good description of the following 2 key points:
First, each Golang process requires only SQL. Open () once
Initially, it is assumed that SQL is the first to have SQL requests every time. Open (). This is actually wrong. Database/sql itself will maintain the connection pool every time SQL. Open () Creates a new set of connection pools. Although there is no error, it can lead to waste of resources. And I found that when the system resources are tight, it causes the goroutine to release, SQL. Db. Close () also failed to resolve.
Second, after each Query (), be sure to remember Row.close ().
The example of the official Golang document is completely free of code about Row.close (). In fact after Query () Be sure to remember defer rows. Close (). If it is not Close, the row will remain dependent on the SQL connection in the current connection pool and the connection will not be freed. Eventually lead to unnecessary accumulation of resources, or even collapse!
Rows, err: = db. Query ("Select name from the Users WHERE age=?", age)
If err! = Nil {log. Fatal (ERR)}
Defer rows. Close ()//parts not mentioned in the documentation
----
The above two improper uses do not cause the code to error, but when the load is high, a leak occurs. I wish #golang lovers not to repeat my mistakes.