Recently, I started using it at work and am learning little by little.
If you want to express it in words easily flush (): Temporarily reflect the query result in the database (rollback is possible, so if you do not commit (), the query will be invalid and you need to commit () at the end) commit (): Permanently reflect the query result in the database (complete addition, update, and deletion of records)
For each use
It is convenient to use flush ()
when you want to roll back in case of an error and make it not reflected in the database.
For example
session.begin()
try:
for item in session.query(Model).all():
session.add(Model)
session.flush() # <-On hold
session.commit() # <-Permanently reflected in the database here
except:
session.rollback() #Discard the hold state and there is no reflection in the database
finally:
session.close() #Error occurs & ends normally, close session in either case
If you don't want to roll back, use commit ()
session.begin()
try:
for item in session.query(Model).all():
session.add(Model)
session.commit() # <-Permanently reflected in the database each time
except Exception as e:
print('Error:{}'.format(str(e)))
raise e
finally:
session.close() #Error occurs & ends normally, close session in either case
Use commit ()
if you want to reflect the processing contents to the database at the end of the processing without causing an error.
The official description is in the official documentation Session.flush(),Session.commit() (It was a little difficult to read the document;)
Other features of commit (), as far as I can tell by reading the official documentation · If you use a session with autocommit = False in default mode, a new transaction is started immediately after the commit.
With this feature, I wonder if session.close () can still be flush () or commit () without creating a session? If anyone can understand it, I would be grateful if you could let me know.
Recommended Posts