I read in the docs :
...since transactions start when a cursor execute a query, but end when COMMIT or ROLLBACK is executed by the Connection object.
import MySQLdb
db = MySQLdb.connect(user="root", db="test")
c = db.cursor()
c.execute("SELECT * FROM books")
print c.fetchall()
I suspect that MySQLdb starts a transaction even on queries that do not modify data (like SELECT), because it is difficult to know if a query only reads data and doesn't write it.
cursor.commit()
after every query, to be sure that no table is locked?Thank you
In a highly concurrent application it could (theoretically) happen that data you've read in the first select is modified before the other selects are executed. If that is a situation that could occur in your application you should use a transaction to wrap your selects.
START TRANSACTION; SELECT @A:=SUM(salary) FROM table1 WHERE type=1; UPDATE table2 SET summary=@A WHERE type=1; COMMIT; With START TRANSACTION , autocommit remains disabled until you end the transaction with COMMIT or ROLLBACK . The autocommit mode then reverts to its previous state.
So one option that you can safely choose is DELETE. CREATE and ALTER are DDL. COMMIT is TCL and is used to permanently save the changes made and ends the transaction after that.
Auto-commit mode means that when a statement is completed, the method commit is called on that statement automatically. Auto-commit in effect makes every SQL statement a transaction. The commit occurs when the statement completes or the next statement is executed, whichever comes first.
Yes, a SELECT
statement is like other so the transaction starts.
If you want to avoid this, you could do something like that:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
SELECT * FROM books ;
COMMIT ;
In detail:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
says that the following instruction could read the rows that have been modified but that haven't received a COMMIT
yet.
That kind of transaction dind't get exclusive locks.
The second part SELECT * FROM books ;
is obviously a SQL statement
and the third part COMMIT ;
ends the transaction and make it "permanent".
In that case no writes are done, so the COMMIT
is used only to end the transaction and
it is true, but it as well automatically commits after each query, because mysql clients start with autocommit=1
by default
you should not, since SELECT
does not hold any locks after the statement is executed. In practice, explicit commits might even cause a significant slow down.
Just might be useful: Why connection in Python's DB-API does not have "begin" operation?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With