In this tutorial, we’ll show see how to delete records from MySQL Database using Python step by step.
1. Setup Required to connect MySQL
To set up the environment, we need to connect MySQL with Python, go through this tutorial to see how to connect MySQL using mysql connector.
If you follow along with the tutorial link, we have connected everything and have code below in our IDE.
# Importing the MySQL-Python-connector import mysql.connector as mysqlConnector # Creating connection with the MySQL Server Running conn = mysqlConnector.connect(host='localhost',user='root',passwd='root') # Checking if connection is made or not if conn: print("Connection Successful :)") else: print("Connection Failed :(") # Creating a cursor object to traverse the resultset cur = conn.cursor() cur.execute("SHOW DATABASES") for row in cur: print(row) # Closing the connection conn.close()
Connection Successful (‘information_schema’,) (‘mysql’,) (‘performance_schema’,) (‘sys’,)
Python Delete Records from MySQL
To delete records from a table we use
delete from <table-name> <condition> SQL query. This helps in deleting records based on the conditions provided. Let us delete the entry rahul having std_id=1. Run the following python code to execute the delete operation.
import mysql.connector as mysqlConnector conn = mysqlConnector.connect(host='localhost',user='root',passwd='root',database='cse') if conn:print("Connection Successful :)") else:print("Connection Failed :(") cur = conn.cursor() try: cur.execute("delete from students where std_id=1 and name='rahul'") print("Query Executed Successfully !!!") conn.commit() for row in cur: print(row) except Exception as e: print("Invalid Query") print(e) conn.close()
After executing this query output the
resultset using the select operator as we have done before. The output will look like this.
(13, 'Kunal', 91001, 'a') (10, 'shubham', 91223, 'a') (31, 'shivam', 91085, 'c')
In this tutorial, we have learned how to perform MySQL CRUD Operations in Python. In case you have any doubts/query, you can ask in the comment section below.
- How to connect MySQL DB with Python
- Insert data into MySQL using Python
- update data in MySQL DB using Python
Happy Learning 🙂