PYTHON Tutorial
In database management, a transaction is a logical unit of work that ensures database consistency. It represents a series of operations that must either succeed or fail together, maintaining data integrity.
Transactions adhere to the following ACID properties:
BEGIN
or START TRANSACTION
.COMMIT
to make the changes permanent. If any error occurs, use ROLLBACK
to undo the entire transaction.Ensuring Data Integrity with MySQL Transactions
import mysql.connector
# Open a database connection
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
# Start a transaction
cursor = connection.cursor()
cursor.execute("BEGIN")
# Execute operations within the transaction
cursor.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 1")
cursor.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 2")
try:
# Commit the transaction
connection.commit()
except Exception as e:
# Rollback the transaction if an error occurs
connection.rollback()
finally:
# Close the cursor and connection
cursor.close()
connection.close()