Sobes.tech
Middle
220

How to find out the number of current connections to the database?

Answer from AI

sobes.tech AI

For PostgreSQL:

SELECT count(*) FROM pg_stat_activity;  -- All active sessions
SELECT count(*) FROM pg_stat_activity WHERE state = 'active'; -- Only currently executing queries

For MySQL:

SHOW STATUS LIKE 'Threads_connected'; // Number of current active connections
SHOW PROCESSLIST; // List of all processes with their current state

For SQLite:

# The number of connections is determined at the application level,
# since SQLite is a file and does not have an embedded network server.
import sqlite3

def get_connections(db_path):
    # Generally, this is the number of Connection objects,
    # created in the application, which are not yet closed.
    # SQLite does not store connection state like a network DBMS.
    pass 

In a Python application, a connection pool is usually used, and the number of active connections can be obtained through its API.

Example with SQLAlchemy:

from sqlalchemy import create_engine

engine = create_engine('postgresql://user:pass@host:port/db', pool_size=10, max_overflow=2)

# Get pool information
pool_status = engine.pool.status() 
print(pool_status) 
# Example output: "Pool size: 10  Connections in pool: 5 Current overflow: 1"
# "Connections in pool" + "Current overflow" - the number of current connections,
# which can be active or waiting.