Junior — Middle
Can you explain how data is written to a database within a transaction?
sobes.tech AI
Answer from AI
In Python, writing data to a database within a transaction is usually implemented using a context manager or explicit transaction management to ensure atomicity of operations. For example, when working with the sqlite3 library, you can use a with block to automatically start and commit a transaction:
import sqlite3
conn = sqlite3.connect('example.db')
with conn:
conn.execute("INSERT INTO users (name, age) VALUES (?, ?)" , ('Ivan', 30))
conn.execute("INSERT INTO users (name, age) VALUES (?, ?)" , ('Maria', 25))
In this example, if one of the insert operations causes an error, all changes will be rolled back. Similarly, in ORM (for example, SQLAlchemy), you can use sessions and the commit() and rollback() methods to manage transactions. A transaction guarantees that either all operations inside the block are successful, or none are applied, which is important for data integrity.