我有一个使用 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/