Junior — Middle
Can you give an example of how transaction isolation is implemented in a database?
sobes.tech AI
Answer from AI
Database transaction isolation ensures that concurrent transactions do not affect each other, preventing issues such as dirty reads, non-repeatable reads, and phantom reads.
Example in Python using SQLAlchemy library and PostgreSQL:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('postgresql://user:password@localhost/dbname')
Session = sessionmaker(bind=engine)
session = Session()
try:
# Set transaction isolation level
session.connection(
execution_options={'isolation_level': 'SERIALIZABLE'}
)
# Begin transaction
session.begin()
# Perform database operations
# ...
session.commit()
except Exception as e:
session.rollback()
print(f'Error: {e}')
finally:
session.close()
Here, the SERIALIZABLE isolation level guarantees maximum transaction isolation. Different DBMSs and drivers may set the isolation level differently, but the essence is that the transaction sees a consistent state of data and does not conflict with other transactions.