SQLAlchemy - Is is necessary to commit after session.execute?
The docs for session.execute say:
Execute a SQL expression construct or string statement within the current transaction.
So, the answer is yes, you need to issue a commit after running session.execute().
Here’s a code example along with the output from “echo=True” showing it begins the session but doesn’t end it unless you run session.commit():
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy import create_engine | |
from sqlalchemy.orm import scoped_session, sessionmaker | |
engine = create_engine('mysql://root@localhost/test') | |
db_session = scoped_session(sessionmaker(bind=engine)) | |
db_session.execute(''' | |
INSERT INTO user (first_name, last_name, username, email) | |
VALUES ("blah", "blah", "blah", "blah@blah.com"); | |
''') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2017-01-16 22:54:11,788 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode' | |
2017-01-16 22:54:11,788 INFO sqlalchemy.engine.base.Engine () | |
2017-01-16 22:54:11,790 INFO sqlalchemy.engine.base.Engine SELECT DATABASE() | |
2017-01-16 22:54:11,790 INFO sqlalchemy.engine.base.Engine () | |
2017-01-16 22:54:11,791 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8' and `Collation` = 'utf8_bin' | |
2017-01-16 22:54:11,791 INFO sqlalchemy.engine.base.Engine () | |
2017-01-16 22:54:11,792 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1 | |
2017-01-16 22:54:11,792 INFO sqlalchemy.engine.base.Engine () | |
2017-01-16 22:54:11,793 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1 | |
2017-01-16 22:54:11,793 INFO sqlalchemy.engine.base.Engine () | |
2017-01-16 22:54:11,794 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin AS anon_1 | |
2017-01-16 22:54:11,794 INFO sqlalchemy.engine.base.Engine () | |
2017-01-16 22:54:11,795 INFO sqlalchemy.engine.base.Engine BEGIN (implicit) | |
2017-01-16 22:54:11,796 INFO sqlalchemy.engine.base.Engine | |
INSERT INTO user (first_name, last_name, username, email) | |
VALUES ("blah", "blah", "blah", "blah@blah.com"); | |
2017-01-16 22:54:11,796 INFO sqlalchemy.engine.base.Engine () |