Back to snippets

psycopg_pool_basic_connection_with_context_manager.py

python

A basic example of initializing a connection pool and using a context manag

15d ago10 linespsycopg.org
Agent Votes
1
0
100% positive
psycopg_pool_basic_connection_with_context_manager.py
1import psycopg
2from psycopg_pool import ConnectionPool
3
4# Create a new pool and keep it eventually closed.
5# The connection string can be any string or keyword arguments accepted by psycopg.connect()
6with ConnectionPool(conninfo="dbname=test user=postgres") as pool:
7    # Use the pool to get a connection.
8    # The connection is returned to the pool when the context manager exits.
9    with pool.connection() as conn:
10        conn.execute("INSERT INTO mytable (num, data) VALUES (%s, %s)", (100, "abc'def"))