[PYTHON] Difference between SQLAlchemy flush () and commit ()

I will explain how to use flush () and commit () properly when manipulating table records using SQLAlchemy, which is one of Python's O / R Mapper.

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

Difference between SQLAlchemy flush () and commit ()
Difference between SQLAlchemy filter () and filter_by ()
Difference between process and job
Difference between "categorical_crossentropy" and "sparse_categorical_crossentropy"
Difference between regression and classification
Difference between np.array and np.arange
Difference between MicroPython and CPython
Difference between ps a and ps -a
Difference between return and print-Python
Difference between Ruby and Python split
Difference between java and python (memo)
Difference between list () and [] in Python
Memorandum (difference between csv.reader and csv.dictreader)
(Note) Difference between gateway and default gateway
Difference between Numpy randint and Random randint
Difference between sort and sorted (memorial)
Difference between python2 series and python3 series dict.keys ()
Difference between SQLAlchemy back_populates and backref and when neither is used
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
[Python] Difference between sorted and sorted (Colaboratory)
[Xg boost] Difference between softmax and softprob
difference between statements (statements) and expressions (expressions) in Python
[Django ORM] Difference between values () and only ()
Difference between @classmethod and @staticmethod in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
Difference between linear regression, Ridge regression and Lasso regression
Difference between docker-compose env_file and .env file
[Python Iroha] Difference between List and Tuple
[python] Difference between rand and randn output
speed difference between wsgi, Bottle and Flask
Difference between numpy.ndarray and list (dimension, size)
Difference between ls -l and cat command
Difference and compatibility verification between keras and tf.keras # 1
What is the difference between `pip` and` conda`?
Difference between using and import on shield language
[python] Difference between variables and self. Variables in class
About the difference between "==" and "is" in python
About the difference between PostgreSQL su and sudo
What is the difference between Unix and Linux?
Consideration of the difference between ROC curve and PR curve
The rough difference between Unicode and UTF-8 (and their friends)
Can BERT tell the difference between "candy (candy)" and "candy (rain)"?
Between parametric and nonparametric
Difference between Ruby and Python in terms of variables
What is the difference between usleep, nanosleep and clock_nanosleep?
Use SQLAlchemy and multiprocessing
Difference between Numpy (n,) and (n, 1) notation [Difference between horizontal vector and vertical vector]
Difference between return, return None, and no return description in Python
How to use argparse and the difference between optparse
What is the difference between a symbolic link and a hard link?
Python module num2words Difference in behavior between English and Russian
Python> Difference between inpbt and print (inpbt) output> [1. 2. 3.] / array ([1., 2., 3.], dtype = float32)
Understand the difference between cumulative assignment to variables and cumulative assignment to objects
List concatenation method in python, difference between list.extend () and “+” operator
The difference between foreground and background processes understood by the principle
Correspondence between pandas and SQL
Conversion between unixtime and datetime
Connection between flask and sqlite3
python metaclass and sqlalchemy declareative