Understanding database transactions and rollback: concepts, examples and Python script implementation

concept

  • Transaction: A transaction in a database is an indivisible set of operations that either all succeed or all fail. This concept guarantees data integrity and consistency.
  • Rollback: When one or more operations in a transaction fail, the rollback mechanism will undo all performed operations and restore the database to the state before the transaction started. This is an error recovery mechanism.
  • Commit: If all operations in the transaction are completed successfully, the transaction is committed and its results are permanently saved in the database.
  • ACID attributes:
    1) Atomicity: Ensure that all operations in the transaction are executed as a whole.
    2) Consistency: The execution of a transaction ensures that the database moves from one consistent state to another consistent state.
    3) Isolation: Ensure that concurrently executed transactions are independent of each other and will not interfere with each other.
    4) Durability: Once a transaction is committed, its results are persisted in the database.

Bank case practice

Create data

In this example, we create a table named accounts, containing two fields: account_id (account ID, as primary key) and balance (account balance). The script will insert two accounts A and B, each with a specific initial balance.

-- 创建银行账户表
CREATE TABLE test.accounts (
    account_id VARCHAR(10) PRIMARY KEY,
    balance DECIMAL(10, 2) NOT NULL
);

-- 插入初始数据
INSERT INTO test.accounts (account_id, balance) VALUES ('A', 1000.00);  -- 假设账户A有1000元
INSERT INTO test.accounts (account_id, balance) VALUES ('B', 500.00);   -- 假设账户B有500元

Transaction rollback in Python script

The following Python script demonstrates how to use transactions in database operations. The script starts with connection.begin(), which marks the beginning of the transaction and attempts to perform a transfer between the two accounts. Failure of any operation will trigger an exception, execute connection.rollback(), and undo all changes. If the operation is successful, the transaction is committed through connection.commit().

import pandas as pd
import pymysql
from credentials import get_credentials
import datetime


def connect_to_database():
    credentials = get_credentials()

    connection = pymysql.connect(
        host='localhost',
        user=credentials['username'],
        password=credentials['password'],
        database='test',
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )

    try:
        with connection.cursor() as cursor:
            current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print(f"{current_time} - 开始事务")
            connection.begin()

            sql_statements = [
                "UPDATE accounts SET balance = balance - 100 WHERE account_id = 'A'",
                "UPDATE accounts SET balance = balance + 100 WHERE account_id = 'B'",
                "select * from accounts;"
            ]

            for sql_statement in sql_statements:
                try:
                    # 执行 SQL 语句
                    cursor.execute(sql_statement)

                    # 获取查询结果
                    result = cursor.fetchall()
                    df = pd.DataFrame(result)

                    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

                    print(f"{current_time} - 正在执行sql: {sql_statement}")
                    print(f"{current_time} - 查询结果如下:")
                    print(df)
                except pymysql.MySQLError as e:
                    # 发生错误时记录错误并准备回滚
                    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    print(f"{current_time} - SQL 错误: {e}")
                    connection.rollback()
                    print("Transaction rolled back.")
                    return  # 结束函数,不再执行后续操作

            # 提交事务
            current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print(f"{current_time} - 提交事务")
            connection.commit()

    except Exception as e:
        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(f"{current_time} - 外部错误: {e}")
        connection.rollback()
        print("Transaction rolled back.")

    finally:
        connection.close()


if __name__ == "__main__":
    connect_to_database()

Additionally, to manage database credentials securely, we use the get_credentials.py module to store and retrieve database usernames and passwords.



def get_credentials():
    # 替换成你实际的用户名和密码
    credentials = {
        'username': 'root',
        'password': '密码'
    }
    return credentials

Conclusion: The key to ensuring data security and integrity

Through this article, we gained an in-depth understanding of the core concepts and importance of database transaction processing. Operations such as Transaction, Rollback and Commit are not only the basis of database management, but also the key to ensuring data security, integrity and consistency.

Summary of importance:

  1. Data Integrity: Transactions ensure that the integrity of the database is not compromised even in the event of errors or system failures.
  2. Error recovery: The rollback mechanism provides an effective error recovery path to protect data from partial operation failures.
  3. Concurrency control: The ACID properties of transactions maintain data consistency and stability in a concurrent environment.

Guess you like

Origin blog.csdn.net/weixin_46211269/article/details/134801426