Sobes.tech
Junior — Middle

Can you give an example of a situation where a transaction is used to ensure data integrity?

sobes.tech AI

Answer from AI

Transactions are used to ensure data integrity when multiple related operations need to be performed atomically—that is, either all operations succeed or none are applied.

Example: transferring money between two accounts in a database. You need to deduct an amount from one account and add it to another. If one operation succeeds and the other fails, the data will be inconsistent.

In Python, using the sqlite3 library, a transaction can look like this:

import sqlite3

conn = sqlite3.connect('bank.db')
cursor = conn.cursor()

try:
    conn.execute('BEGIN')
    cursor.execute('UPDATE accounts SET balance = balance - 100 WHERE id = 1')
    cursor.execute('UPDATE accounts SET balance = balance + 100 WHERE id = 2')
    conn.commit()  # confirm the transaction
except Exception as e:
    conn.rollback()  # revert changes on error
    print('Error during transfer:', e)
finally:
    conn.close()

Thus, if one of the balance update operations fails, the changes are not saved, and the data remains consistent.