- read

Understanding ACID Transactions in DB Operations with Python

Ebo Jackson 45

ACID transactions are an essential concept in database management systems (DBMS) that ensure the correctness, consistency, and reliability of database operations. ACID stands for Atomicity, Consistency, Isolation, and Durability [2]. In this article, we will explore the significance of ACID transactions and provide practical examples using SQL statements in Python.

A transaction is a single logical unit of work that accesses and modifies the contents of a database [1]. It can consist of one or more SQL statements, but for it to be considered successful, either all the SQL statements must complete successfully or none at all. This ensures that the database remains in a new stable state or reverts to the state before the transaction began.

Let’s consider an example of an online transaction involving three SQL statements. Suppose Rose buys a pair of boots for $200 from a shoe shop. The transaction requires the following updates to the database:

  1. Decrease Rose’s account balance by $200
  2. Increase the Shoe Shop’s account balance by $200
  3. Decrease the stock level of boots at the Shoe Shop by 1

To implement this transaction in Python, you can use a database-specific access API, such as ibm_db for Python, to execute the SQL statements [3]. Here’s an example code snippet:

import ibm_db

# Connect to the database
conn = ibm_db.connect("DATABASE=your_database;HOSTNAME=your_hostname;PORT=your_port;PROTOCOL=TCPIP;UID=your_username;PWD=your_password;", "", "")

# Begin the transaction implicitly

# Execute the SQL statements
stmt1 = ibm_db.exec_immediate(conn, "UPDATE accounts SET balance = balance - 200 WHERE customer = 'Rose'")
stmt2 = ibm_db.exec_immediate(conn, "UPDATE accounts SET balance = balance + 200 WHERE customer = 'Shoe Shop'")
stmt3 = ibm_db.exec_immediate(conn, "UPDATE inventory SET stock = stock - 1 WHERE product = 'boots'")

# Commit the transaction if all statements executed successfully
print("Transaction successful!")

# Rollback the transaction if any statement fails
print("Transaction failed!")

# Close the database connection

In this example, the transaction begins implicitly, and the SQL statements are executed using the ibm_db module. If all the statements complete successfully, the transaction is committed, ensuring all the changes are saved in a consistent state. However, if any statement fails, the transaction is rolled back, undoing all the changes made during the transaction.

Using PostGreSQL to illustate same example:

import psycopg2

# Connect to the database
conn = psycopg2.connect(database="your_db_name", user="your_username", password="your_password", host="your_host", port="your_port")
cur = conn.cursor()

# Begin ACID transaction

# SQL statements for the transaction
cur.execute("UPDATE accounts SET balance = balance - 200 WHERE customer_name = 'Rose';")
cur.execute("UPDATE store_accounts SET balance = balance + 200;")
cur.execute("UPDATE inventory SET stock = stock - 1 WHERE product_name = 'Boots';")

# If all statements succeed, commit the transaction
print("Transaction successfully committed.")
except Exception as e:
# If any statement fails, rollback the transaction
print("Transaction rolled back due to:", str(e))

# Close the connection

It’s important to note that ACID transactions provide the following properties:

Atomicity: All changes made within a transaction must be performed successfully or not at all. In our example, if any of the UPDATE statements fail, the entire transaction will fail, ensuring data consistency.

Consistency: The database must be in a consistent state before and after the transaction. In our example, the account balance, store balance, and stock level must be updated correctly to maintain data integrity.

Isolation: While a transaction is running, no other process should be able to change the data. This prevents data inconsistencies and conflicts. In our example, if another transaction tries to update the stock level of boots simultaneously, it will be blocked until the current transaction completes.

Durability: Once a transaction is committed, its changes are permanent and will persist even in the event of system failures. The updates and modifications made by the transaction are written to disk and stored in non-volatile memory.

In conclusion, understanding ACID transactions is crucial for maintaining data integrity and consistency in DB operations. By implementing ACID transactions in your code, you can ensure that your database remains in a reliable state even in the face of failures. Using practical examples like the online transaction involving SQL statements in Python, you can apply ACID principles to real-world scenarios and build robust database applications.