Python SQLite connection.rollback() Function



The Python connection.rollback function retrieves all changes made in the current transaction and releases any database held by the connection. This function is particularly useful when a transaction fails or an exception is raised.

In SQLite, a connection refers to an active link between the application and database. This connection allows us to execute SQL commands and queries in the database.

The rollback function is used to maintain data integrity . It undergoes all changes made in the current transaction; if an error occurs, then the database remains constant.

Syntax

Following is the syntax for the connection.rollback() function.

conn.rollback()

Parameters

This function doesn't take any parameters.

Return Value

This connection.rollback() function has no return value.

Example 1

In the below example, we are going to insert employee names into the table using connection.rollback function.

cursor.execute("INSERT INTO employees (first_name) VALUES (%s), ()%s", ('John', 'Ben'))
conn.rollback()

Output

The result is obtained as follows −

first_name
-------------
John
Ben

Example 2

Here, we are deleting the row from the database using connection.rollback() function.

cursor.execute("DELETE FROM employees WHERE first_name = ?", ('John',))
print("Row deleted")
print("Transaction rolled back")

Output

The output is obtained as follows −

Row deleted
Transaction rolled back
python_modules.htm
Advertisements