1. 使用Python实现MySQL数据库事务的银行转账代码示例
import mysql.connector
def transfer_funds(from_account_id, to_account_id, amount):
try:
# 连接到MySQL数据库
connection = mysql.connector.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
cursor = connection.cursor()
# 开始事务
connection.start_transaction()
# 从转出账户扣除金额
subtract_query = "UPDATE accounts SET balance = balance - %s WHERE account_id = %s AND balance >= %s"
cursor.execute(subtract_query, (amount, from_account_id, amount))
if cursor.rowcount == 0:
raise Exception("Insufficient funds in the source account.")
# 向转入账户增加金额
add_query = "UPDATE accounts SET balance = balance + %s WHERE account_id = %s"
cursor.execute(add_query, (amount, to_account_id))
# 提交事务
connection.commit()
print("Funds transferred successfully.")
except mysql.connector.Error as err:
# 发生错误时回滚事务
if connection.is_connected():
connection.rollback()
print(f"Error: {err}")
finally:
# 关闭游标和连接
if cursor:
cursor.close()
if connection.is_connected():
connection.close()
2. 事务处理过程中可能出现的错误及异常处理
- 数据库连接错误:在尝试连接MySQL数据库时可能会出现错误,例如主机名错误、用户名或密码错误、数据库不存在等。可以通过捕获
mysql.connector.Error
异常来处理这类错误,并在捕获到异常时给出相应的错误提示,如上面代码中的except mysql.connector.Error as err
块。
- 资金不足错误:在从转出账户扣除金额时,如果转出账户的余额不足,更新语句将不会影响任何行。此时可以通过检查
cursor.rowcount
的值来判断是否有足够的资金,如果rowcount
为0,则抛出一个自定义异常,如raise Exception("Insufficient funds in the source account.")
,并在异常处理块中回滚事务。
- 其他数据库操作错误:在执行SQL语句过程中可能会出现其他错误,如SQL语法错误、约束违反等。同样通过捕获
mysql.connector.Error
异常来处理这些错误,并在捕获到异常时回滚事务,以确保数据的一致性和完整性。回滚操作通过connection.rollback()
实现,确保在发生错误时,之前对数据库的修改不会被提交。