How the global connection pool works
masterThe library uses connection pooling to reuse database connections across multiple requests in a single Node.js process. The sql.connect() function manages a single global connection pool.
Key behaviors:
- Singleton Pattern: There can only be one global connection pool connected at a time. Subsequent calls to
sql.connect()with different configurations will not create a new connection if a pool is already connected. - Idempotency: If the global pool is already connected,
sql.connect()resolves immediately to the existing pool. - Lifecycle: Do not call
sql.close()after individual queries, as this destroys the pool for the entire application. Only callsql.close()when the application is shutting down (e.g., in a CLI tool or CRON job).
It is recommended to await or .then() the pool creation to ensure it is ready before executing queries.
const sql = require('mssql')
const config = { ... }
// run a query against the global connection pool
function runQuery(query) {
// sql.connect() will return the existing global pool if it exists or create a new one if it doesn't
return sql.connect(config).then((pool) => {
return pool.query(query)
})
}