在现代数据库开发中,DataGrip 等工具通过提供图形界面来提交、回滚或设置保存点,使事务处理变得更容易。
在本文中,我们将在 SQL 中定义 COMMIT、ROLLBACK 和 SAVEPOINT 并演示如何在使用 Oracle、MySQL 或Python 中的 PostgreSQL。
关键交易概念定义:完成事务,使所有更改永久保存在数据库中。
•
用例:当事务中的所有操作都成功时使用COMMIT,确保数据库反映更改。
定义:恢复事务期间所做的所有更改,将数据库恢复到之前的状态。
•
用例:使用ROLLBACK 处理错误或撤消失败的事务。
定义:在事务中设置命名检查点,允许部分回滚到该点而不撤消整个事务。
•
用例:使用SAVEPOINT 管理多个步骤的复杂事务,在需要时有选择地回滚。
Python 中事务的常见步骤
import cx_Oracle # Connect to Oracle Database connection = cx_Oracle.connect("user/password@localhost/XEPDB1") cursor = connection.cursor()
try: # Start Transaction cursor.execute("UPDATE Accounts SET Balance = Balance - 100 WHERE Name = 'Alice'") cursor.execute("UPDATE Accounts SET Balance = Balance + 100 WHERE Name = 'Bob'") # Commit the transaction connection.commit() print("Transaction committed successfully!") except Exception as e: # Rollback in case of error connection.rollback() print(f"Transaction failed. Rolled back changes. Error: {e}")
try: # Start Transaction cursor.execute("UPDATE Accounts SET Balance = Balance - 200 WHERE Name = 'Alice'") connection.commit() # Savepoint cursor.execute("SAVEPOINT Savepoint_After_Alice") # Add 200 to Bob (intentional error to demonstrate rollback) cursor.execute("UPDATE Accounts SET Balance = Balance + 200 WHERE Name = 'Unknown'") # Commit if successful connection.commit() except Exception as e: # Rollback to savepoint cursor.execute("ROLLBACK TO Savepoint_After_Alice") connection.commit() print(f"Rolled back to savepoint. Error: {e}")概括
感谢您花时间与我一起探索与数据相关的见解。感谢您的参与。
?在 LinkedIn 上与我联系
以上是SQL 事务 - 使用 Python 提交、回滚和保存点的详细内容。更多信息请关注PHP中文网其他相关文章!