In a Go program, attempting to insert data into a PostgreSQL table using a single database connection for each message received from RabbitMQ resulted in an error due to exceeding the maximum number of connections.
The issue lies in the way SQL queries are executed in Go. sql.DB is a connection pool rather than a single connection. It opens connections as needed and reuses idle connections, but in this case, the connections were not being released properly.
The problem arises when using db.QueryRow without calling Scan on the returned *Row value. *Row holds a reference to a connection, which is automatically released when Scan is called. However, in the provided code, Scan was not being called, causing the connections to pile up in the connection pool.
To resolve this, the solution is to either use db.Exec if the output is not required, or to call Scan on the *Row value returned by db.QueryRow.
The above is the detailed content of How Can I Avoid PostgreSQL Connection Exhaustion When Inserting Rows in Go?. For more information, please follow other related articles on the PHP Chinese website!