python - 在 django 中的单个 connection.cursor 上执行多个。安全吗?

标签 python django database-connection database-cursor django-database

我正在用 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/

相关文章:

python - Django + Gunicorn + Nginx : Bad Request (400) in Debug=True

java - 听/通知 pgconnection 关闭 java?

java连接mysql数据库失败

python - 如何在二进制转换程序中的python中每4位之后创建一个空格

python - 将 Python Flask 应用程序拆分为多个文件

python - 从 C++ 代码转换时 python 代码出现故障?

python - 使用 Celery 成功执行一个函数后运行另一个任务

python - 已从数据库中删除的图像也从存储中删除

python - 比带条件的 iterrows 更快的方法(每行的前驱和后继)

c# - 无法读取配置部分 'connectionStrings',因为它缺少部分声明