What is the difference between session.commit() and session.flush()?
Does anybody know what the main difference between session.commit()
and session.flush(开发者_StackOverflow)
in SQLAlchemy is?
The easiest way I know how to explain what these do is to just show you, using echo=True
:
>>> session.flush()
BEGIN (implicit)
INSERT INTO users (username, password) VALUES (?, ?)
('alice', None)
>>> session.commit()
COMMIT
>>>
flush()
causes the data to be sent to the database. commit()
causes a COMMIT
, which tells the database to keep the data that was just sent. As others have stated, commit()
will also cause a flush()
to occur, if it's needed.
Here are some relevant quotes from the documentation.
flush:
When the
Session
is used with its default configuration, the flush step is nearly always done transparently. Specifically, the flush occurs before any individual Query is issued, as well as within thecommit()
call before the transaction is committed.
commit:
commit()
is used to commit the current transaction. It always issuesflush()
beforehand to flush any remaining state to the database; this is independent of the “autoflush” setting. If no transaction is present, it raises an error. Note that the default behavior of the Session is that a “transaction” is always present; this behavior can be disabled by settingautocommit=True
. In autocommit mode, a transaction can be initiated by calling thebegin()
method.
Straight from the documentation:
commit()
is used to commit the current transaction. It always issuesflush()
beforehand to flush any remaining state to the database.
Although the above answers are correct, the most useful feature of flush is in applying the changes made to the table in the database back into the concerned object in the code. Here is an example, Suppose you register a user and you want to give back his id,
u = User(name,address,phone) #id is autogenerated
session.add(u)
session.commit() #calls flush beforehand, but we need it after the commit
session.flush() #updates the objects of the session
print(u.id) #id field of the User object updated after the flush
You need not query again to get his id!! Hope this helps
flush()
will synchronize your database with the current state of object/objects held in the memory but it does not commit the transaction. So, if you get any exception afterflush()
is called, then the transaction will be rolled back. You can synchronize your database with small chunks of data usingflush()
instead of committing a large data at once usingcommit()
and face the risk of getting anOut Of Memory
exception.
commit()
will make data stored in the database permanent. There is no way you can rollback your transaction once thecommit()
succeeds.
Source: https://stackoverflow.com/a/26976077/4115031
精彩评论