×

Performing Transaction Using Python MySQL

Transaction

A Transaction contains a set of SQL commands used to change the data in the dataset. If we say transaction, it means that the data in the database has changed. It is used to change the database from one consistent state to another. It is a logical set of instructions to modify or change the dataset and maintain its consistency.

A transaction can be understood with an example if we want to withdraw money from account X and deposit it in account Y, then this can be a transaction.

A transaction is made up of ACID property, and these four properties are:

  1. Atomicity: In this property, all transactions will be successful or none. It’s either all or none. If any of the commands fail, then the entire transaction will fail. Either transaction will complete, or nothing will happen at all.
  2. Consistency: In this property, a transaction should always acquire a consistent state. From the start to the end, a transaction should be consistent.
  3. Isolation: In this property, any transaction that is happening should not be visible to any other transaction. It should be isolated. Its intermediate result should not be visible to any other transaction.
  4. Durability: In this property, if a transaction has been committed, its effect must be persistent even if the system fails.

Python provides two methods to perform transactions which are commit and rollback.

Steps to perform transactions in Python MySQL

  • Create MySQL database in Python.
  • Collect or prepare the set of queries you want to perform. It can be multiple queries in one transaction.
  • Set an auto-commit property of MySQL to false.
  • Execute all the queries one by one using cursor.execute().
  • If the queries get executed successfully, then commit the changes to the database.
  • If any of the queries get blocked or failed, then we will rollback all the changes.
  • We will also catch the SQL exception in this process.
  • Close the cursor and MySQL database.

Python commit () method

The python commit() method is used to maintain the database’s consistency. In the database, if any changes occur in the transaction, then it must be consistent; for that, we use the commit method.

The method will send a COMMIT statement to the MySQL server, which then commits the current transaction. When execution of the query is successful, it makes permanent changes in a database using the commit() of the connection class.

The syntax for commit() method is given below:

connec.commit()   # connec is the connection object

Any operation that we perform in a transaction to modify the database will not occur until we don’t call the commit method.

Python rollback() method

The Python rollback() method is used if any of the queries in the transaction doesn’t get executed or fail. In that case, we use the rollback method.

The syntax for rollback() method is given below:

connec.rollback()  # connec is the connection object

Python autoCommit() method

It is used to enable or disable the value of auto-commit as true or false. By default, its value is taken as False.

The syntax for autoCommit() method is given below:

connec.autocommit() # connec is the connection object

In the python DB-API, we perform transaction processing through the connection object model. We will invoke begin() to begin the transaction in the database and after that, we can use commit or rollback to end it. The begin() call and the commit() call goes into the same block whereas the rollback() block goes into the corresponding except block which will cancel the transaction if any error occurs.

Let’s understand with an example. In this transaction we will withdraw and deposit money from one person to another.

try:
   conn.begin ( )
   cursor = conn.cursor ( )
   # move some money from one person to the other
   cursor.execute ("UPDATE money SET amt = amt - 10 WHERE name =    'Sam'")
   cursor.execute ("UPDATE money SET amt = amt + 10 WHERE name = 'Eva'")
   cursor.close ( )
   conn.commit( )
except MySQLdb.Error, er:
   print "Transaction failed, rolling back. Error was:"
   print er.args
   try: 
     # if the rollback fails then we will use exception handler
     conn.rollback ( )
   except:
     pass

Explanation

  • In the above code, we can see that after successful execution of the queries, we committed our changes to the database using a conn.commit().
  • In case of an exception or failure of one of the queries, we can revert our changes using a conn.rollback().
  • We placed all our code in the try-except block to catch the database exceptions that may occur during the process.

Related Topics

Python Project Ideas

One of the most widely used programming languages today is Python. This pattern appears set to continue through 2023 and beyond. Therefore, working on some current Python project ideas is the...

10 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 minutes read.

Binary Search Visualization using Pygame in Python

A calculation like Binary Search is seen effectively by picturing. Here in this tutorial, a function that pictures the Binary Search Algorithm is carried out. The Graphical User’s Interface (GUI)...

15 minutes read.

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.

Python Time Library

We will consider various functions given by the python module library with examples.This python time module helps to work on time in python to get the current time.Before going with...

4 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

Check Palindrome in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Get Bounding Box Co-ordinates Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

Python Decorator

Python Decorator: A Decorator is an interesting feature of Python that helps the user design patterns and insert a new functionality to an existing object without making any modifications in...

6 minutes read.

Python Word Tokenizer

Python Overview Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. Python is an interpreted language...

4 minutes read.

Self in Python

 “self" is neither a keyword nor has a special meaning in Python, but it has a place and a job to do in Object-oriented programming. When we create a class...

6 minutes read.

Python JSON Schema

Python-jsonschema JSON: JSON stands for JavaScript Object Notation. It is a text-based format that represents structured data and can be used to interchange data among various applications. This is self-defining language...

5 minutes read.

Python Boolean

In this article, you will learn the boolean variables in python, bool() function in python, and bool operators with examples, Boolean Objects in Python. There are the only two possible values...

6 minutes read.

Notepad++ For Python

In this article, you are going to learn what notepad++ is and how it is integrated with python to use the python programming language. You can also learn how to...

4 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Check whether dir is empty or not in python

Python: Check if a directory is empty In this tutorial, we will study how to check whether the director (dir) is empty or not in the python programming language. First of...

3 minutes read.

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

Python if statement

Python if statement Decision making is an essential feature of any programming languages. Condition checking is the strength of decision making. Python provides many decision-making statements, such as: If statementIf-else statementelif statement if statement The if statement is...

2 minutes read.

Python Array

Python Array In the programming language or computer science, an array is defined as the form of a data structure which consists of or store collection of various types of elements...

10 minutes read.