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:
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.
Syntax:
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.
Example:
Program to update the age of a student named Rishi Kumar and commit it to the database.
MySQL Table in use:

Python3
import mysql.connector
mydb = mysql.connector.connect(
host = 'localhost' ,
database = 'College' ,
user = 'root' ,
)
cs = mydb.cursor()
statement = "UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'"
cs.execute(statement)
mydb.commit()
mydb.close()
|
Output:

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.
Syntax:
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:
Python3
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try :
mydb = mysql.connector.connect(
host = 'localhost' ,
database = 'College' ,
user = 'root' ,
)
cs = mydb.cursor()
statement = "UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'"
cs.execute(statement)
mydb.commit()
print ( "Database Updated !" )
except mysql.connector.Error as error :
print ( "Database Update Failed !: {}" . format (error))
mydb.rollback()
mydb.close()
|
Output:
If the database transaction is successful the output will be,
Database Updated!
If the database transaction fails the output is an error raised as,
Database Update Failed!
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!