I got an error as follows in my code of python (which collects twitter statuses and store in database).
sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back by a nested rollback() call. To begin a new transaction, issue Session.rollback() first.
I want to know what is the problem, why does it occur, and how can I solve it.
I have no idea about nested rollback
. Is there any simple example which occurs nested rollback
?
The “autocommit” feature is only in effect when no Transaction has otherwise been declared. This means the feature is not generally used with the ORM, as the Session object by default always maintains an ongoing Transaction .
flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction.
connection() method at the start of a transaction: from sqlalchemy. orm import Session # assume session just constructed sess = Session(bind=engine) # call connection() with options before any other operations proceed. # this will procure a new connection from the bound engine and begin a real # database transaction.
The problem was solved. The point, in this case, is that rollback is not executed until we call rollback explicitly, so when we include commit()
, we should write it in a try statement, and write rollback()
in the exception statement (in most case) as written in https://docs.sqlalchemy.org/en/13/faq/sessions.html#this-session-s-transaction-has-been-rolled-back-due-to-a-previous-exception-during-flush-or-similar
And, here is the correct code example. I quoted this from the link above.
try: <use session> session.commit() except: session.rollback() raise finally: session.close() # optional, depends on use case
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