How to reuse a single Postgres DB connection for row inserts in Go?

后端 未结 1 1910
攒了一身酷
攒了一身酷 2020-12-07 02:55

I\'m trying to use Go to insert a row of data into a Postgres table for each new message received from rabbitmq, using a single connection to the DB which is opened in the

相关标签:
1条回答
  • 2020-12-07 03:14

    First off, *sql.DB is not a connection but a pool of connections, it will open as many connection as it needs to and as many as the postgres server allows. It only opens new connections when there is no idle one in the pool ready for use.


    So the issue is that the connections that DB opens aren't being released, why? Because you're using QueryRow without calling Scan on the returned *Row value.

    Under the hood *Row holds a *Rows instance which has access to its own connection and that connection is released automatically when Scan is called. If Scan is not called then the connection is not released which causes the DB pool to open a new connection on the next call to QueryRow. So since you're not releasing any connections DB keeps opening new ones until it hits the limit specified by the postgres settings and then the next call to QueryRow hangs because it waits for a connection to become idle.

    So you either need to use Exec if you don't care about the output, or you need to call Scan on the returned *Row.

    0 讨论(0)
提交回复
热议问题