我正在用 connection.cursor 打开游标,执行一系列删除,然后关闭游标。它有效,但我不确定它是否有任何副作用。非常感谢任何反馈。
from django.db import connection
c=connection.cursor()
try:
c.execute('delete from table_a')
c.execute('delete from table_b')
...
finally:
c.close()
最佳答案
由于您不是在事务中执行这些 SQL 语句,因此您可能会遇到令人困惑的状态(例如,数据已从 table_a
中删除,但未从 table_b
中删除)。
Django documentation谈到这种特殊情况:
If you’re executing several custom SQL queries in a row, each one now runs in its own transaction, instead of sharing the same “automatic transaction”. If you need to enforce atomicity, you must wrap the sequence of queries in atomic().
因此,每个 execute()
调用的结果都会在它之后立即提交,但我们希望它们要么全部通过,要么全部失败 - 作为一组更改。
用 transacton.atomic
包装 View 装饰者:
from django.db import transaction
@transaction.atomic
def my_view(request):
c = connection.cursor()
try:
c.execute('delete from table_a')
c.execute('delete from table_b')
finally:
c.close()
注意 atomic()
和整个 new transaction management system在 Django 1.6 中引入。
如果您使用的 Django < 1.6,请申请 transaction.commit_on_success
装饰器。
关于python - 在 django 中的单个 connection.cursor 上执行多个。安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25592804/