Sobes.tech
Intern

What is connection pool in the database/sql package? How does it work?

sobes.tech AI

Answer from AI

Connection pool in the database/sql package is a mechanism for managing a set of open connections to a database that are reused to execute queries. Instead of opening and closing a connection for each query, the pool maintains several active connections, which significantly improves performance and reduces the load on the database.

How it works:

  • When the first query is made, a new connection is created and added to the pool.
  • Subsequent queries take a free connection from the pool.
  • If all connections are busy, the query waits for a connection to be freed or a new connection is created if the limit has not been reached.
  • After use, the connection is returned to the pool for reuse.

Example of pool configuration in Go:

import "database/sql"

// db — *sql.DB
// Set the maximum number of open connections
 db.SetMaxOpenConns(10)
// Set the maximum number of idle connections
 db.SetMaxIdleConns(5)
What is connection pool in the database/sql package… - sobes.tech