AI Hints
Home›PostgreSQL Tutorial›Postgres from Python
PostgreSQL · Lesson 84 of 120

Transactions in Python

Commit or roll back.

⏱ 2 min read▶ Video at 1:15:43🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

In psycopg, every connection starts a transaction automatically. Nothing is saved until you commit. The transaction block makes this clear, and rolls back if anything fails.

  • Auto transaction
  • Commit to save
  • Roll back on error

All or nothing in Python

Inside conn dot transaction, both statements succeed, or neither does. The second insert breaks a rule, so the exception rolls back the first one too. Run it. The order count is unchanged.

tx.pypython
import psycopg

conn = psycopg.connect("postgresql://postgres:postgres@localhost:5432/riverside")
count = "SELECT count(*) FROM orders"
print("before:", conn.execute(count).fetchone()[0])

add = "INSERT INTO orders (customer_id, order_date, status) VALUES (%s, now(), 'new')"
try:
    with conn.transaction():
        conn.execute(add, (1,))      # a real customer
        conn.execute(add, (9999,))   # no such customer
except psycopg.errors.ForeignKeyViolation:
    print("rolled back")
print("after: ", conn.execute(count).fetchone()[0])
Output
before: 1598
rolled back
after:  1598

Transaction tips

Use with conn dot transaction for clear boundaries. Or call commit and rollback yourself. Autocommit mode runs each statement on its own. And keep transactions short, especially in web apps.

keyvalue
conn.transaction()block
commit / rollbackmanual
autocommit=Trueeach statement
Shortalways

Summary

Psycopg wraps work in transactions, and the transaction block commits or rolls back for you. Next, loading lots of data with copy.

Key takeaways
  • transaction()
  • commit
  • rollback
Next up: COPY and Bulk Loading — the fast way in