I think there is a misunderstanding about what constitutes a transaction here.
In this example, one connection is opened, then one transaction is executed. You execute several SQL transactions in this transaction, but completely close them after committing. Of course, this is more than normal.
Performing multiple transactions (as opposed to just SQL statements) is as follows:
conn = MySQLdb.connect(host="1.2.3.4", port=1234, user="root", passwd="x", db="test") for j in range(10): try: for i in range(10): cur = conn.cursor() query = "DELETE FROM SomeTable WHERE ID = %d" % i cur.execute(query) cur.close() conn.commit() except Exception: conn.rollback() conn.close()
The above code makes 10 transactions, each of which consists of 10 separate delete operators.
And yes, you should be able to reuse an open connection for this without problems, unless you are sharing this connection between threads.
For example, SQLAlchemy reuses connections by merging them, distributing open connections as needed for the application. New transactions and new instructions are executed in these connections throughout the life of the application, without the need to close them until the application is closed.
source share