python - 无法使用 Django ORM 关闭脚本中的自动提交

标签 python mysql django command-line

我有一个使用 Django ORM 和 MySQL 后端的命令行脚本。我想关闭自动提交并手动提交。对于我的一生,我无法让它发挥作用。这是脚本的简化版本。每次我运行它时都会在 testtable 中插入一行,并且我从 MySQL 收到此警告:“一些非事务性更改的表无法回滚”。

#!/usr/bin/python

import os
import sys

django_dir = os.path.abspath(os.path.normpath(os.path.join(os.path.dirname(__file__), '..')))
sys.path.append(django_dir)

os.environ['DJANGO_DIR'] = django_dir
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

from django.core.management import setup_environ
from myproject import settings

setup_environ(settings)

from django.db import transaction, connection
cursor = connection.cursor()
cursor.execute('SET autocommit = 0')
cursor.execute('insert into testtable values (\'X\')')
cursor.execute('rollback')

我还尝试将插入放在函数中并添加 Django 的 commit_manually 包装器,如下所示:

@transaction.commit_manually
def myfunction():
    cursor = connection.cursor()
    cursor.execute('SET autocommit = 0')
    cursor.execute('insert into westest values (\'X\')')
    cursor.execute('rollback')

myfunction()

我还尝试在 settings.py 中设置 DISABLE_TRANSACTION_MANAGEMENT = True,但没有成功。我觉得我错过了一些明显的东西。非常感谢您能给我的任何帮助。谢谢!

最佳答案

你的表是 MyISAM 还是 InnoDB?请记住 MyISAM 不是事务性的,因此不能回滚。参见示例 this page在 MySQL 文档中:

In transactional terms, MyISAM tables effectively always operate in autocommit = 1 mode.

关于python - 无法使用 Django ORM 关闭脚本中的自动提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2473090/

相关文章:

php - 部分匹配 MySQL 查询

mysql - 将列从 Database2 添加到 Database1

php - 组件安装后 Joomla SQL 查询错误

django - Paypal 运输选项

javascript - 如何最初隐藏表单,但在屏幕重新加载时呈现表单?

python - 如何使 QMenu 中的图标变大(PyQt)?

python - 'Axes3DSubplot' 对象没有属性 'voxels'

python - MongoEngine 和处理 "UserWarning: MongoClient opened before fork. Create MongoClient with connect=False, or create client after forking"

python - 将所有剩余参数传递给 Nose 的 flask 脚本命令?

python - ctype 为什么指定 argtypes