w3resource

Python and PostgreSQL: A Complete Guide to Psycopg2


Working with PostgreSQL Using Psycopg2 in Python

Psycopg2 is a popular PostgreSQL adapter for Python. It provides efficient and secure interaction with PostgreSQL databases, supporting advanced features such as transactions, connection pooling, and asynchronous operations.

1. Installation

Install Psycopg2 using pip:

pip install psycopg2

2. Connecting to PostgreSQL

Establish a connection to the PostgreSQL database using the connect() method:

import psycopg2

conn = psycopg2.connect(
    dbname="your_database",
    user="your_username",
    password="your_password",
    host="localhost",
    port="5432"
)
print("Connected successfully")

3. Executing Queries

a. Create a Cursor

Cursors allow you to execute queries:

cur = conn.cursor()

b. Execute a Query

cur.execute("SELECT * FROM table_name")
rows = cur.fetchall()
for row in rows:
    print(row)

c. Commit Changes (if needed)

For INSERT, UPDATE, or DELETE queries:

Copy code
cur.execute("INSERT INTO table_name (column1, column2) VALUES (%s, %s)", (value1, value2))
conn.commit()

4. Error Handling

Handle exceptions to manage database errors gracefully:

try:
    conn = psycopg2.connect(...)
    cur = conn.cursor()
    cur.execute("SELECT * FROM table_name")
except psycopg2.Error as e:
    print("Database error:", e)
finally:
    cur.close()
    conn.close()

5. Using Connection Pooling

To improve performance, use a connection pool with psycopg2.pool:

from psycopg2.pool import SimpleConnectionPool
pool = SimpleConnectionPool(1, 10, dsn="...")
conn = pool.getconn()

6. Advanced Features

Feature Description Example
Asynchronous Queries Use psycopg2 with async operations. psycopg2.connect(async_=True)
Prepared Statements Optimize performance for repetitive queries. PREPARE and EXECUTE SQL commands
Transaction Control Manage database transactions explicitly. conn.commit() and conn.rollback()

Additional Notes:

  • Security:Use environment variables or secret management tools for credentials.
  • Compatibility:Ensure PostgreSQL and psycopg2 versions are compatible.

All PostgreSQL Questions, Answers, and Code Snippets Collection.



Become a Patron!

Follow us on Facebook and Twitter for latest update.