问题
I'm reading about how do transactions work in python's MySQLdb
. In this tutorial, it says that:
In Python DB API, we do not call the BEGIN statement to start a transaction. A transaction is started when the cursor is created.
So a following line:
cur = con.cursor()
starts a transaction implicitly. It also says, that:
We must end a transaction with either a commit() or a rollback() method.
Do I understand it correctly, that MySQLdb
uses transactions always and there's no way to turn this behavior off? Forcing user to enclose all queries in transactions seems a bit strange. If so - is there any explanation why is that?
回答1:
I'm not a huge expert in this, but I think the feature you're looking for here is autocommit. This automatically commits your commands. Therefore you should be able to skip the 'BEGIN' statements.
Here's a page on it: http://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
You set this up when you start the python MySQLdb instance:
conn=MySQLdb.connect(host='blah', autocommit=True)
You should then have a connection that doesn't worry about Transactions.
Some storage engines don't use transactions so if you use one, you won't need to worry about this detail: en.wikipedia.org/wiki/Comparison_of_MySQL_database_engines
However, they can run into issues if your insert \ update fails halfway through!
来源:https://stackoverflow.com/questions/24121284/python-mysqldb-without-transactions