Junior — Middle
How is operation management carried out within a single database transaction?
sobes.tech AI
Answer from AI
Managing operations within a single transaction in a database is usually done using a transaction mechanism that guarantees atomicity, consistency, isolation, and durability (ACID). In Python, when working with a database through libraries such as sqlite3 or psycopg2, a transaction starts automatically or explicitly, and changes are committed with the commit command or rolled back with rollback.
Example using sqlite3:
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
cursor.execute("INSERT INTO accounts (user_id, balance) VALUES (last_insert_rowid(), 1000)")
conn.commit() # commit changes
except Exception as e:
conn.rollback() # rollback changes on error
print(f"Error: {e}")
finally:
conn.close()
Thus, all operations inside the block are either applied together or not at all.