MySQL事务处理失败:回滚示例
在MySQL中,当一个事务中的SQL操作全部执行成功,才会提交;若有一个或多个操作失败,就需要回滚。
以下是使用Python的mysql-connector-python
库进行回滚示例:
import mysql.connector
# 创建数据库连接
cnx = mysql.connector.connect(user='username', password='password',
host='localhost',
database='database_name')
cursor = cnx.cursor()
# 事务开始
cursor.execute("START TRANSACTION")
# 发布SQL操作,这里假设所有操作都在同一个表上
try:
# 操作1
cursor.execute("INSERT INTO table (column) VALUES ('value')")]
# 操作2
cursor.execute("UPDATE table SET column = 'new_value' WHERE condition = 'some_condition'")
except Exception as e:
print(f"Error occurred: {e}")
# 如果所有操作都成功,提交事务
cursor.execute("COMMIT")
cursor.close()
cnx.close()
请将上述代码中的username
、password
、localhost
、database_name
、table
、column
等替换为你的实际数据库信息。
还没有评论,来说两句吧...