Commit & RollBack Operation in Python
Python’s commit() method and rollback() method are among the various methods used for making database transactions. Database transactions are necessary as they ensure the atomicity, consistency, isolation and durability of the database.
In this article, we will focus on the use of commit() and rollback() method in detail.
1. The commit() method:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
The commit() method is used to make sure the changes made to the database are consistent. It basically provides the database confirmation regarding the changes made by a user or an application in the database.
comm.commit() #comm refers to the database connection object
For a better understanding of the concept look into the code below followed by the code explanation. The below demonstration of the commit() method is performed on a MySQL database.
Program to update the age of a student named Rishi Kumar and commit it to the database.
MySQL Table in use:
2. The rollback() method:
The rollback() method is used to revert the last changes made to the database. If a condition arises where one is not satisfied with the changes made to the database or a database transaction fails, the rollback() method can be used to retrieve the original data that was changed through the commit() method.
comm.rollback() #comm refers to the database connection object
The below code shows the use of rollback() method to revert changes if a database transaction fails:
If the database transaction is successful the output will be,
If the database transaction fails the output is an error raised as,
Database Update Failed!