Home »
Python »
Python programs
Delete a Record from the Database in Python
Here, we are going to see a Python program to delete a specific record from the database using the id entered by the user.
Submitted by Shivang Yadav, on February 19, 2021
Problem Statement: Program to delete record from Database using the id entered by the user.
Solution:
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 the 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', deleted record.
Python program to delete a Record from the Database
import cpymysql as mysql
try:
conn=mysql.connect(host='localhost',port=3306,user='root',password='123',db='myschool')
cmd=conn.cursor()
id=input("Enter Faculty Id U Want To Delete:")
q="select * from faculties where fid='{}'".format(id)
cmd.execute(q)
row=cmd.fetchone()
if(row==None):
print("Not Found")
else:
print("ID:",row[0])
print("Name:", row[1])
print("Birth Date:", row[2])
print("Department:", row[3])
print("Salary:", row[4])
ch=input("Are you Sure(yes/no)?")
if(ch=='yes'):
q="delete from faculties where fid={}".format(id)
cmd.execute(q)
conn.commit()
print("Record Deleted....")
conn.close()
except Exception as e:
print("Error:",e)
Output:
Enter Faculty Id U Want To Delete: 03
ID: 03
Name: John
Birth Data: 12.4.1988
Department: computer Science
Salary: 45000
Are you Sure(yes/no)?yes
Record Deleted....
Python database (SQL/MySQL) programs »
ADVERTISEMENT
ADVERTISEMENT