×

Python MySQL Delete Operation

Python MySQL Delete Operation: Like the update operation where we were updating required field from a SQL table, we can also delete an entry from the table which we have made by performing INSERT operation on the table. We can delete any entry from the table using the DELETE method in our Python program to perform this operation on SQL table.

Note: While performing DELETE operation on SQL table we must ensure that we have used WHERE clause with the DELETE method in our Python program otherwise all the entries from the table will be removed. The where clause will used to specify which entry we want to delete from the table.

Syntax: Following syntax we need to follow when we are performing Delete operation on SQL tables through Python program:

> delete from TableName where id = ID

Now, we will use this DELETE method on our 'StudentTable' to delete two entries in two different examples and then we print the table after deleting the specific entry. We will use the following syntax in the two examples:

> delete from StudentTable where id = ID (ID of students)

Consider the following two examples:

Examples 1: Deleting an entry from StudentTable using Delete operation on it where id = 2601:

 # import the mysql.connector module
 import mysql.connector
 # create the connection object with database
 MyConnectionObject = mysql.connector.connect(host = "localhost", user = "root",passwd = "2401", database = "OurPython1stDB")
 # print the defined connection object
 print(MyConnectionObject)
 # define the cursor object with cursor() function
 CursorObject = MyConnectionObject.cursor()
 # print the defined cursor object
 print(CursorObject)
 # use DELETE FROM method in try and catch method
 try: 
     CursorObject.execute("delete from Studenttable where id = 2601") # Entry field where ID = 2601 deleted from the table
     MyConnectionObject.commit() # it commits the updation in the StudentTable
     print("The entry field in StudentTable where id = 2601 is successfully removed from the table.")
 except: 
     MyConnectionObject.rollback()
 # print the updated table using fetchall() function on cursorobject
 CursorObject.execute("SELECT * FROM StudentTable")
 ResultOutput = CursorObject.fetchall()
 # print the updted table with for loop
 for z in ResultOutput:
   print(z)
 # close the connection using close() function
 MyConnectionObject.close() 

Output:

 <mysql.connector.connection.MySQLConnection object at 0x0000024832C97CD0>
 MySQLCursor: (Nothing executed yet)
 The entry field in StudentTable where id = 2601 is successfully removed from the table.
 ('Jonas', 2401, 'Science', 'A', 'Physics')
 ('Delta', 2402, 'Science', 'A', 'Physics')
 ('Lyon', 2509, 'Science', 'B', 'Maths')
 ('Peter', 2703, 'Science', 'C', 'Biology')
 ('Jonathan', 2901, 'Science', 'E', 'Biotechnology') 

Example 2: Deleting an entry from StudentTable using Delete operation on it where id = 2402:

 # import the mysql.connector module
 import mysql.connector
 # create the connection object with database
 MyConnectionObject = mysql.connector.connect(host = "localhost", user = "root",passwd = "2401", database = "OurPython1stDB")
 # print the defined connection object
 print(MyConnectionObject)
 # define the cursor object with cursor() function
 CursorObject = MyConnectionObject.cursor()
 # print the defined cursor object
 print(CursorObject)
 # use DELETE FROM method in try and catch method
 try: 
     CursorObject.execute("delete from Studenttable where id = 2402") # Entry field where ID = 2402 deleted from the table
     MyConnectionObject.commit() # it commits the updation in the StudentTable
     print("The entry field in StudentTable where id = 2402 is successfully removed from the table.")
 except: 
     MyConnectionObject.rollback()
 # print the updated table using fetchall() function on cursorobject
 CursorObject.execute("SELECT * FROM StudentTable")
 ResultOutput = CursorObject.fetchall()
 # print the updated table with for loop
 for z in ResultOutput:
   print(z)
 # close the connection using close() function
 MyConnectionObject.close() 

Output:

 <mysql.connector.connection.MySQLConnection object at 0x0000024832C97CD0>
 MySQLCursor: (Nothing executed yet)
 The entry field in StudentTable where id = 2402 is successfully removed from the table.
 ('Jonas', 2401, 'Science', 'A', 'Physics')
 ('Lyon', 2509, 'Science', 'B', 'Maths')
 ('Peter', 2703, 'Science', 'C', 'Biology')
 ('Jonathan', 2901, 'Science', 'E', 'Biotechnology') 

Explanation: In the above two examples, we have first imported mysql.connector module in our Python program to access MySQL database. Then, we have defined a connection object named 'MyConnectionObject' in the program.

We have used connect() method on 'MyConnectionObject' with specifying the database. Then, we have printed the connection object we have defined. After that, we have used cursor() function to define a cursor object in the program with name CursorObject. After that we have printed the cursor object.

Then, we used Try and catch method in our program to perform the Delete operation. Then we used the execute() function with the CursorObject and after that we have used DELETE FROM method with the where clause i.e., where ID = 2402 or 2901. Using where clause after FROM keyword specifically indicates which entry we want to remove from the table. In the first example we have removed entry of student where ID = 2601 and in second example we have removed entry of student where ID = 2402.

Then, we used commit() function with connection object to commit this updation in the table in database. After that, we have closed 'try and catch' method using the rollback() function with MyConnectionObject in catch statement. Then, we have used fetchall() function with the cursor object to define the ResultOutput through which we will print the updated table in the output of the program.

We used ResultOutput inside the for loop in our program so that we can easily print updated table as output of program. Then, we closed the connection with database using close() function with MyConnectionObject. Output will be printed after Python successfully run the program and access the database.

  • We can use DELETE FROM method in any Python program like this we have used in above two examples to update any field from a given SQL table. We just have to specify the table name and use the where clause by specifying the ID of entry that we want to remove from the table.

Related Topics

Python Os sep

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

3 minutes read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

3 minutes read.

How to check the version of the Python Interpreter?

As we all know what an interpreter is, and how important it is. We should also be aware of the fact that it is important to have knowledge of the...

2 minutes read.

Python set()

Python set() Class The set() class in Python returns a new set object, optionally with elements taken from iterable.  Syntax class set([iterable]) Parameter iterable : This parameter represents a sequence, collection or an iterator object Return This function returns a...

1 minute read.

Arguments and parameters in Python

Generally, there is a misunderstanding that parameters and arguments, both are the same. But, as a programmer, you need to understand the difference between these two. Parameters: While defining a function, we...

5 minutes read.

Allocate a minimum number of pages in python

You have given a sorted array of size n which represents the number of pages in n different books and an integer value which denotes the number of students. We...

4 minutes read.

Python Set union() method

Python Set union() method The set.union() method in Python returns a set that contains all items from the original set and all items from the specified sets. Syntax set.union(set1, set2...) Parameter set1- This parameter represents the first set...

2 minutes read.

An Introduction to Mocking in Python

Python Mocking is a testing library. It enables you to substitute portions of your system under test with fake(mock) objects and make assertions about how they were utilized.  The test is...

3 minutes read.

Best resources to learn Numpy and Pandas in python

In this tutorial, we will discuss the different resources where we can learn about NumPy and Pandas libraries of Python in a more efficient way. NumPy NumPy, a Python library used for...

4 minutes read.

List Subtract in Python

The List is one of the most unique Data Structures in Python. It is generally used to store multiple values in just one single variable. It is one of the...

4 minutes read.

Python str() function

Python str() function The str() function in Python converts the specified value into a string. Syntax class str(object='')           or class str(object=b'', encoding='utf-8', errors='strict') Parameter object:  This parameter represents any object to convert the given...

1 minute read.

AX Contour in Python

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.

Traverse Dictionary in Python

Traversing a dictionary is visiting each and every step in the dictionary, which is also called iterating the dictionary In Python, dictionaries are a useful and commonly used data structure in...

3 minutes read.

Python complex() class

Python complex() class The complex() class in Python returns a complex number or converts a string or number to a complex number. Syntax class complex([real[, imag]]) Parameter Real: This parameter consists of a number representing the real...

1 minute read.

PyShark in 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....

4 minutes read.

Best books for NLP with Python

NLP NLP – Natural language processing Computers were created to make the life of mankind easier. But computers cannot understand human language. Instead, they interact with numbers to perform the tasks allotted...

12 minutes read.

Type casting in Python

Introduction Type Casting is defined as the method of converting the variables/values data type into a certain data type for matching the operation needed to be performed by the users. This...

4 minutes read.

Anaconda in Python 3

What is Anaconda in Python 3? Anaconda is an open-source package combining Python and R programming languages used for data analytics and processing data. It consists of a huge number of...

4 minutes read.

Python Comment Block

In this tutorial, we will see what comment blocks mean in Python. Further, we will see the commenting methods supported in Python. We will understand the topics deeply with the...

6 minutes read.

Python Skyline

Python Programming Language: 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...

3 minutes read.