Skip to Content
Databases in Flask - Reading, Updating and Deleting
Session: add and rollback

A set of operations such as addition, removal, or updating database entries is called a database transaction. A database session consists of one or more transactions. The act of committing ends a transaction by saving the transactions permanently to the database. In contrast, rollback rejects the pending transactions and changes are not permanently saved in the database.

In Flask-SQLAlchemy, a database is changed in the context of a session, which can be accessed as the session attribute of the database instance. An entry is added to a session with the add() method. The changes in a session are permanently written to a database when .commit() is executed.

For example, we create new readers and would like to add them to our database:

from app import db, Reader new_reader1 = Reader(name = "Nova", surname = "Yeni", email = "") new_reader2 = Reader(name = "Nova", surname = "Yuni", email = "") new_reader3 = Reader( name = "Tom", surname = "Grey", email = "")

Note that we didn’t specify the primary key id value. Primary keys don’t have to be specified explicitly, and the values are automatically generated after the transaction is committed.

Adding each new entry to the database has the same pattern:

db.session.add(new_reader1) try: db.session.commit() except: db.session.rollback()

Notice that we surrounded db.session.commit() with a try-except block. Why did we do that? If you look more carefully, new_reader1 and new_reader2 have the same e-mail, and when we declared the Reader model, we made the e-mail column unique (see the file). As a consequence, we want to undo the most recent addition to the transaction by using db.session.rollback() and continue with other additions without interruption.



In the file, create a variable called new_reader that is assigned an instance of the Reader class with name = “Peter”, surname = “Johnson”, and email Do not add an assignment for id(the id will be automatically generated once the entry is added to the database)


In the “” file, using session.add() add the new_reader entry to the database.


In the “” file, commit the new_reader object to the database. Enclose it using try-except. If except happens, perform the rollback.

Folder Icon

Sign up to start coding

Already have an account?