在 Django 程序中的数百个 MySQL UPDATE 语句期间禁用自动提交
在 Django 程序中,如何在数百个 UPDATE 之前显式禁用自动事务管理并在 UPDATE 完成后启用它?
我调查了 http://docs.djangoproject.com/en/dev/topics /db/transactions/ 但没有找到任何线索。
我尝试将以下代码放在开头
settings.DISABLE_TRANSACTION_MANAGEMENT = True
我也尝试了
cursor = connection.cursor()
cursor.execute('SET SESSION autocommit = 0;')
...
UPDATE
...
cursor.execute('SET SESSION autocommit = 1;')
上面的方法都没有提高更新速度。上面的代码有什么问题吗?
In a Django program, how to explicitly disable auto transaction management before hundreds of UPDATEs and enable it after the UPDATEs finish?
I looked into http://docs.djangoproject.com/en/dev/topics/db/transactions/ but didn't find any clue.
I tried to put the following code at the beginning
settings.DISABLE_TRANSACTION_MANAGEMENT = True
I also tried
cursor = connection.cursor()
cursor.execute('SET SESSION autocommit = 0;')
...
UPDATE
...
cursor.execute('SET SESSION autocommit = 1;')
Neither methods above improved the updating speed. Is there anything wrong with above codes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这将允许您运行任何您想要运行的 SQL,然后仅在没有异常的情况下提交。如果您像示例中那样使用手动光标,则需要 set_dirty() 调用,但如果您只使用 Django ORM,则不需要调用 set_dirty() (如果我没记错的话;这至少是 1.2 行为)。
要完全控制事务,您可以使用 transaction.commit_manually 装饰器。至于你的速度问题,我无法评论。
django 文档很好地解释了这一点: http: //docs.djangoproject.com/en/dev/topics/db/transactions/#django.db.transaction.commit_on_success
This will let you run whatever SQL you want to run, and then only commit if there are no exceptions. The set_dirty() call is required if you're using a manual cursor as in your example, but won't be required if you just use the Django ORM (if I'm not mistaken; this is 1.2 behaviour at least).
To have full control over the transactions, you can use the transaction.commit_manually decorator. As for your speed issue, I can't comment.
The django docs explain this pretty well: http://docs.djangoproject.com/en/dev/topics/db/transactions/#django.db.transaction.commit_on_success
如果您只进行数百次更新而不是数万次更新,则速度问题可能不是由于写入数据而导致,而是由于查找数据而导致。即,更新语句中可能有一个 where 子句,并且需要一段时间才能找到要更新的正确行。如果是这种情况,那么关闭自动提交不会有帮助 - 您需要在 where 子句中的字段上建立索引。
表中有多少行?
更新语句是什么样的?
您也可以尝试准备好的语句,但是对于不到一千次的更新,它应该不会产生太大的差异。
If you're only doing hundreds of updates and not tens of thousands, maybe the speed issue isn't due to writing the data, but due to finding it rather. i.e. perhaps there's a where clause in the update statement and it takes a while to find the correct row to update. If that's the case then turning off autocommit wouldn't help - you'd need an index on the field in your where clause.
How many rows are in the table?
What does the update statement look like?
You could also try prepared statements, but for under a thousand updates it shouldn't make much of a difference.