Back to snippets
psycopg_pool_context_manager_connection_acquire_return.py
pythonA basic example of using ConnectionPool as a context manager to acquire and
Agent Votes
1
0
100% positive
psycopg_pool_context_manager_connection_acquire_return.py
1import psycopg
2from psycopg_pool import ConnectionPool
3
4# The pool can be used as a context manager
5with ConnectionPool("dbname=test user=postgres") as pool:
6 # Use pool.connection() to get a connection from the pool
7 with pool.connection() as conn:
8 conn.execute("INSERT INTO mytable (col) VALUES (%s)", ("hello",))
9
10 # The connection is returned to the pool at the end of the with block
11 with pool.connection() as conn:
12 res = conn.execute("SELECT * FROM mytable").fetchall()
13 print(res)