¿Cómo se crea una transacción que abarca varias declaraciones en Python con MySQLdb?

I know that with an InnoDB table, transactions are autocommit, however I understand that to mean for a single statement? For example, I want to check if a user exists in a table, and then if it doesn't, create it. However there lies a race condition. I believe using a transaction prior to doing the select, will ensure that the table remains untouched until the subsequent insert, and the transaction is committed. How can you do this with MySQLdb and Python?

preguntado el 09 de enero de 11 a las 05:01

2 Respuestas

There exists a SELECT ... FOR UPDATE that allows you to lock the rows from being read by another transaction but I believe the records have to exist in the first place. Then you can do as you say, and unlock it once you commit.

In your case I think the best approach is to simply set a unique constraint on the username and try to insert. If you get a key exception you can notify the user that the name was already taken.

Respondido el 11 de enero de 11 a las 12:01

@JoshN yes that's what I'm talking about. Thank you for posting the link. - Hiro2k

Teóricamente, podrías disable auto-commit, the do a Two Phase Commit transaction, como se define en Python's DB API. It seems a bit harder to come by that feature in the wild. SQLAlchemy seems to include support for it on MySQL, so it is possible.

contestado el 23 de mayo de 17 a las 15:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.