Junior — Middle
How is transaction management implemented in PostgreSQL?
sobes.tech AI
Answer from AI
In PostgreSQL, transaction management is performed using SQL commands: BEGIN (start of transaction), COMMIT (confirm changes), and ROLLBACK (undo changes). A transaction is a sequence of operations executed as a single unit. If an error occurs during the process, all changes can be rolled back.
In Python, when working with PostgreSQL through libraries such as psycopg2, transactions are usually managed automatically or manually:
import psycopg2
conn = psycopg2.connect(...)
cur = conn.cursor()
try:
conn.autocommit = False # disable autocommit
cur.execute("INSERT INTO table_name (col) VALUES ('value')")
conn.commit() # confirm the transaction
except Exception as e:
conn.rollback() # rollback on error
print(f"Error: {e}")
finally:
cur.close()
conn.close()
Also, in modern versions of psycopg2, you can use a context manager for automatic transaction management.