Home »
Python »
Python programs
Python program to delete a record from database using its ID (Example 2)
Here, we will see a Python program to delete a record from the database using an ID entered by the user.
Submitted by Shivang Yadav, on March 06, 2021
We will use Python's PyMySql library to work with the database. This library provides the programmer the functionality to run MySQL query using Python.
Algorithm:
- Step 1: Connect to database using connect() method in pymysql.
- Step 2: Get input of faculty ID from the user.
- Step 3: Write a query to fetch the details of the faculty and display it to the user.
- Step 4: Get confirmation input from the user.
- Step 5: If 'Yes', delete the record and print "Record Deleted".
Program to delete a record from database using its ID
import pymysql as MYSQL
try:
conn=MYSQL.connect(host='localhost',port=3306,
user='root',password='123',db='practice')
cmd=conn.cursor()
id=input("Enter Product Id U Want to Delete:")
q="select * from products where productid={}".format(id)
cmd.execute(q)
row=cmd.fetchone()
if(row==None):
print("Record Not Found")
else:
#print(row)
print("Product Id:",row[0])
print("Product Name:",row[1])
print("Product Price:",row[2])
print("Product Date:",row[3])
ch=input("Are U Sure Yes/No?")
if(ch.lower()=='yes'):
q="delete from products where productid={}".format(id)
cmd.execute(q)
print("Record Deleted....")
conn.commit()
conn.close()
except Exception as e:
print(e)
Output:
Enter Product Id U Want to Delete:47
Product ID:47
Product Name:cPhone Prime
Product Price:12499
Product Date: 27/10/2020
Are U Sure yes/no?yes
Record Deleted...
Python database (SQL/MySQL) programs »