django 資料庫 mysql 事務 處理
阿新 • • 發佈:2020-07-14
顯式控制事務¶
Django 提供了一個 API 控制資料庫事務。
atomic
(using=None,savepoint=True)¶-
原子性是資料庫事務的定義屬性。
atomic
允許建立程式碼塊來保證資料庫的原子性。如果程式碼塊成功建立,這個變動會提交到資料庫。如果有異常,變動會回滾。atomic
塊可以巢狀。在這個例子裡,當內部塊成功完成時,如果在稍後外部塊裡引發了異常,則仍可回滾到最初效果。atomic
既可用作decorator:: :from django.db import transaction @transaction.atomic def viewfunc(request):
也可用作context manager:: :
from django.db import transaction def viewfunc(request): # This code executes in autocommit mode (Django's default). do_stuff() with transaction.atomic(): # This code executes inside a transaction.
在 try/except 塊中使用裝飾器
atomic
來允許自然處理完整性錯誤:from django.db import IntegrityError, transaction @transaction.atomic def viewfunc(request): create_parent() try: with transaction.atomic(): generate_relationships() except IntegrityError: handle_exception() add_children()
事務回滾¶
第一個選項是回滾整個事務。比如:
a.save() # Succeeds, but may be undone by transaction rollback try: b.save() # Could throw exception except IntegrityError: transaction.rollback() c.save() # Succeeds, but a.save() may have been undone
呼叫
transaction.rollback()
回滾整個事務。任何未提交的資料庫操作會被丟棄。在這個例子裡,a.save()
做的改變會丟失,即使操作本身沒有引發錯誤。儲存點回滾¶
你可以使用savepoints來控制回滾的程度。執行可能失敗的資料庫操作之前,你可以設定或更新儲存點;這樣,如果操作失敗,你可以回滾單一的錯誤操作,而不是回滾整個事務。比如:
a.save() # Succeeds, and never undone by savepoint rollback sid = transaction.savepoint() try: b.save() # Could throw exception transaction.savepoint_commit(sid) except IntegrityError: transaction.savepoint_rollback(sid) c.save() # Succeeds, and a.save() is never undone
在這個例子裡,
a.save()
將不會在b.save()
引發異常的情況下被撤銷。宣告 : 轉載自 Django 官方中文庫文件。
連結 :https://docs.djangoproject.com/zh-hans/3.0/topics/db/transactions/#django.db.transaction.rollback