×

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 Dictionary keys() method

Python Dictionary keys() method The dictionary.keys() method in Python returns a view object that displays a list of all the keys in the dictionary Syntax dictionary.keys() Parameter NA Return This method returns a view object that displays...

2 minutes read.

Cx_Oracle Python with Example

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 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.

Write a String 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...

5 minutes read.

Python Sys Stdout

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python e-book free download

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. There are many sources to learn python. In this...

3 minutes read.

Python Dictionary copy() method

Python Dictionary copy() method The dictionary.copy () method in Python returns a copy of the specified dictionary. Syntax dictionary.copy () Parameter NA Return None Example 1 # Python program explaining # the dictionary.copy() method # initialising the dictionary ...

1 minute read.

Polymorphism in Python

What is polymorphism and why is it important? Polymorphism's literal definition is the state of occurring in diverse shapes or forms. When it comes to programming, the idea of polymorphism is crucial....

3 minutes read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

Add in Dictionary Python

Dictionary in python: Dictionaries are a useful data configuration for storing information in Python because they can mimic real-world data arrangements where a particular value exists for a particular key. The...

4 minutes read.

How To Print Colored Text in Python

Changing the colour of certain parts of a string when printing the output of a Python programme to the terminal may make it easier to read. We can approach this...

3 minutes read.

Dynamic Typing in Python

Many key factors for developing a great programming language include how it manages its memory space. This memory space largely depends on empty memory boxes called variables that one creates...

3 minutes read.

Reading a File Line by Line in Python

Introduction In this tutorial, we will learn about reading files in python line by line. Before reading the files, let us know a little information about the files first. Files A file is...

6 minutes read.

Python Set Methods

[et_pb_section][et_pb_row][et_pb_column type="4_4"][et_pb_text] Python Set Methods A set is a collection which is unordered and unindexed. Python has a set of built-in methods that you can use on sets. Methods ...

4 minutes read.

Gaussian elimination in python

Linear and polynomial equations are used in almost all fields of numerical simulation. However, its most common use in engineering is in the area of linear system analysis. The broader...

3 minutes read.

Python String

Python String Python string is considered as the most popular data type present in Python language. In Python, string data type is the collection of characters, letters, white spaces etc. written...

31 minutes read.

Python Typing Module

An Introduction to the Typing Module The typing module is introduced in Python version 3.5 and used to provide hinting method types in order to support static type checkers and linters...

10 minutes read.

Python Linear regression

In this tutorial, we will understand the meaning, usage, and types of Linear Regression. Further, we will comprehend the terms cost function and Optimization. Linear Regression is the widely used Machine...

3 minutes read.

Method Overloading in Python

Overloading is a capability of a method and operator to behave differently according to the nature of parameters. Overloading is popular because it provides a good number of advantages: Reusability of code.Reduces...

3 minutes read.

Weight Conversion GUI using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.