Junior — Middle
How to determine the number of active database connections at the moment?
sobes.tech AI
Answer from AI
The determination of the number of active connections to a database depends on the used DBMS and driver. In Python, you can execute an SQL query that returns the current number of connections.
For example, for PostgreSQL:
import psycopg2
conn = psycopg2.connect(dbname="yourdb", user="user", password="pass", host="localhost")
cur = conn.cursor()
cur.execute("SELECT count(*) FROM pg_stat_activity WHERE datname = current_database();")
active_connections = cur.fetchone()[0]
print(f"Active connections: {active_connections}")
cur.close()
conn.close()
For MySQL, you can use:
cur.execute("SHOW STATUS WHERE `variable_name` = 'Threads_connected';")
active_connections = cur.fetchone()[1]
Thus, you need to execute the appropriate query to the database to get the number of active connections.