MST

星途 面试题库

面试题:Python使用MySQLdb库处理复杂事务

假设有两个MySQL数据库表`accounts`(包含字段`account_id`、`balance`)和`transactions`(包含字段`transaction_id`、`from_account_id`、`to_account_id`、`amount`)。请使用Python的MySQLdb库编写代码实现一个转账操作:从`from_account_id`账户扣除`amount`金额,同时向`to_account_id`账户增加`amount`金额,要求使用事务确保操作的原子性,即要么全部成功,要么全部失败。并且在操作完成后返回操作是否成功的结果。
15.2万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import MySQLdb


def transfer_money(from_account_id, to_account_id, amount):
    try:
        # 连接数据库
        conn = MySQLdb.connect(host='localhost', user='your_username', passwd='your_password', db='your_database')
        cursor = conn.cursor()
        # 开启事务
        conn.autocommit(False)
        # 从from_account_id账户扣除amount金额
        subtract_sql = "UPDATE accounts SET balance = balance - %s WHERE account_id = %s"
        cursor.execute(subtract_sql, (amount, from_account_id))
        # 向to_account_id账户增加amount金额
        add_sql = "UPDATE accounts SET balance = balance + %s WHERE account_id = %s"
        cursor.execute(add_sql, (amount, to_account_id))
        # 提交事务
        conn.commit()
        conn.autocommit(True)
        cursor.close()
        conn.close()
        return True
    except MySQLdb.Error as e:
        # 发生错误回滚事务
        if conn:
            conn.rollback()
            conn.autocommit(True)
        print(f"操作失败: {e}")
        return False


你可以使用以下方式调用这个函数:

if __name__ == "__main__":
    result = transfer_money(1, 2, 100)
    print(f"转账操作是否成功: {result}")


在上述代码中:

  1. 首先使用MySQLdb.connect连接到MySQL数据库。
  2. 通过设置conn.autocommit(False)开启事务。
  3. 执行两个UPDATE语句分别对两个账户进行金额的增减操作。
  4. 如果操作过程中没有错误,调用conn.commit()提交事务。
  5. 如果发生错误,通过conn.rollback()回滚事务,确保数据的一致性。
  6. 最后关闭游标和数据库连接,并返回操作是否成功的结果。

请根据实际的数据库配置替换hostuserpasswddb等参数。