×

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

SKLearn Clustering

These are ml methods thatare responsible for detecting patterns and the similarities within the data.The clustering methods are unsupervised.Here the data is clustered to form groups with the help of...

3 minutes read.

Python Compiler

What is Compiler? The compiler is mainly a program used to convert the source code into the machine or binary code. The source code is generally a computer program written using...

6 minutes read.

Python program to perform the arithmetic operation

Python program to perform the arithmetic operation This program will write a code to perform some basic arithmetic operations like addition, subtraction, multiplication, exponent, modulus, and division. Here we first need...

2 minutes read.

Python Struct

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.

Assertion Errors and Attribute Errors in Python

Assertion Error in Python In Python, the assert condition is used to continue the execution if the given statement displays true. If the assert statement displays false, it raises Assertion Error...

3 minutes read.

JWT Decode Python

Python's PyJWT package makes it possible to encrypt and decrypt JSON Web Tokens (JWT). JWT is a public, recognized global benchmark for safely expressing demands between two parties (RFC 7519). JSON...

7 minutes read.

Python Set isdisjoint() method

Python Set isdisjoint() method The set.isdisjoint() method in Python returns a boolean value True if two sets are disjoint sets ( i.e. none of the elements are present in both sets), otherwise it returns...

1 minute read.

Python Parallel Processing

By performing more jobs concurrently, your software may complete more tasks in a shorter amount of time. These aid in solving major issues. The following subjects will be covered in...

2 minutes read.

Filter List in Python

Python: Python is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a user-friendly programming...

3 minutes read.

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.

How to comment out a block of code in Python

When you are writing code in Python, you may want to document it. You need to mention why a piece of code functions, for instance. Mathematics, algorithms, and intricate business...

4 minutes read.

Python pycountry

What is Pycountry? 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...

4 minutes read.

Python open() function

Python open() function The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised. Syntax open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Parameter file It represents the path and name of the file mode...

2 minutes read.

Convert XML to JSON in Python

XML conversion is very useful if we work on an API that returns data in JSON format and the source of data is in XML format. JSON A JSON file reserves the...

4 minutes read.

Python Empty Tuple

How to Create an Empty Tuple Tuple A tuple is a data structure used to store non-homogeneous data elements. These non-homogeneous data elements consist of integer data type, character data type, String...

3 minutes read.

How to reverse a string in python

How to reverse a string in python A Brief About Strings- The String is a data type in Python that has a sequence of characters. This series of characters are represented in...

4 minutes read.

Python Identifiers

Identifiers in Python User-defined names are identifiers in Python that are used to name variables, functions, classes, modules, and other things. You can create Python identifiers using these rules: As an identifier...

4 minutes read.

Spotify API in Python

The application programming interface is referred to as API. In essence, an API serves as a layer of communication or, as the name suggests, an interface that enables systems to...

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.

What is the Python Global Interpreter Lock?

Introduction When working with processes, Python employs a form of process lock called the Global Interpreter Lock (GIL). Python typically executes a collection of typed statements using just one thread. It...

4 minutes read.