Class 12 Programs
- 1.Read text file line by line with # separator
- 2.Count vowels, consonants, uppercase, lowercase in file
- 3.Remove lines containing character 'a'
- 4.Binary file with name and roll number search
- 5.Binary file update marks by roll number
- 6.Random number generator (Dice Simulator)
- 7.Stack implementation using list
- 8.CSV file with user-id and password
- 9.User Defined Functions to manipulate List Store Indices of Non Zero elements &Double the Odd values
- 10.WORKING WITH BINARY FILE IN PYTHON Create a binary file, Search and display the records from the binary file
- 11.TEXT FILES IN PYTHON Remove duplicate lines from the file & Display unique words present in the file
- 12.TEXT FILES IN PYTHON Copying lines to a new file & Replacing the '-' sign with a blankspace
- 13.TEXT FILES IN PYTHON Count the lines starts with I/T & Display the lines with exactly 6 words
- 14.TEXT FILES IN PYTHON Count the occurrences of word & Count number of vowels and consonants
- 15.User Defined Functions to Manipulate List Find the Longest Word and Shifting the elements to left
- 16.IMPLEMENTATION OF STACK USING LIST IN PYTHON
- 17.ALTER table to add new attributes / modify data type / drop attribute
- 18.UPDATE table to modify data
- 19.ORDER By to display data in ascending / descending order
- 20.DELETE to remove tuple(s)
- 21.GROUP BY and find the min, max, sum, count and average
- 22.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - DELETE RECORDS
- 23.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - UPDATE RECORDS
- 24.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - INSERT RECORDS
Quick Tips
- • Import random module for number generation
- • Use randint(1, 6) for dice simulation
- • Handle user input validation properly
INTERFACING PYTHON WITH MYSQL - DELETE RECORDS
AIM
To write a Python program to interface with MySQL database and delete records from a table based on specific conditions.
ALGORITHM
- Start
- Import mysql.connector module
- Establish connection to MySQL database
- Create cursor object
- Display all records before deletion
- Accept condition for deletion from user
- Execute DELETE query with WHERE clause
- Commit the transaction
- Display confirmation message
- Display remaining records after deletion
- Close cursor and connection
- Stop
PROGRAM
# Python program to delete records from MySQL database
import mysql.connector
def connect_database():
"""Establish connection to MySQL database"""
try:
connection = mysql.connector.connect(
host='localhost',
database='school',
user='root',
password='password'
)
return connection
except mysql.connector.Error as error:
print(f"Error connecting to MySQL: {error}")
return None
def display_records(cursor):
"""Display all records from students table"""
cursor.execute("SELECT * FROM students")
records = cursor.fetchall()
if records:
print("\n--- Student Records ---")
print("ID\tName\t\tAge\tGrade")
print("-" * 40)
for record in records:
print(f"{record[0]}\t{record[1]:<12}\t{record[2]}\t{record[3]}")
else:
print("No records found in the table.")
def delete_records():
"""Main function to delete records"""
connection = connect_database()
if connection is None:
return
cursor = connection.cursor()
try:
# Display records before deletion
print("Records before deletion:")
display_records(cursor)
# Get deletion criteria from user
print("\nDelete records based on:")
print("1. Student ID")
print("2. Age")
print("3. Grade")
choice = input("Enter your choice (1-3): ")
if choice == '1':
student_id = input("Enter Student ID to delete: ")
query = "DELETE FROM students WHERE id = %s"
values = (student_id,)
elif choice == '2':
age = input("Enter age (delete all students with this age): ")
query = "DELETE FROM students WHERE age = %s"
values = (age,)
elif choice == '3':
grade = input("Enter grade (delete all students with this grade): ")
query = "DELETE FROM students WHERE grade = %s"
values = (grade,)
else:
print("Invalid choice!")
return
# Execute delete query
cursor.execute(query, values)
# Check if any records were deleted
if cursor.rowcount > 0:
connection.commit()
print(f"\n{cursor.rowcount} record(s) deleted successfully!")
# Display records after deletion
print("\nRecords after deletion:")
display_records(cursor)
else:
print("No records found matching the criteria.")
except mysql.connector.Error as error:
print(f"Error deleting records: {error}")
connection.rollback()
finally:
cursor.close()
connection.close()
print("\nDatabase connection closed.")
# Main program
if __name__ == "__main__":
print("=== MySQL Database - Delete Records ===")
delete_records()OUTPUT
=== MySQL Database - Delete Records ===
Records before deletion:
--- Student Records ---
ID Name Age Grade
----------------------------------------
1 John Smith 18 A
2 Jane Doe 17 B
3 Mike Johnson 18 A
4 Sarah Wilson 16 C
Delete records based on:
1. Student ID
2. Age
3. Grade
Enter your choice (1-3): 2
Enter age (delete all students with this age): 18
2 record(s) deleted successfully!
Records after deletion:
--- Student Records ---
ID Name Age Grade
----------------------------------------
2 Jane Doe 17 B
4 Sarah Wilson 16 C
Database connection closed.
CONCLUSION
The program successfully demonstrates how to delete records from a MySQL database using Python. It shows proper database connection handling, user input validation, transaction management with commit/rollback, and displays records before and after deletion for verification.
VIVA QUESTIONS
What is the purpose of the DELETE statement in SQL?
The DELETE statement is used to remove existing records from a table based on specified conditions in the WHERE clause.
Why is it important to use WHERE clause with DELETE?
Without WHERE clause, DELETE will remove all records from the table. WHERE clause specifies which records to delete.
What is the purpose of commit() and rollback() methods?
commit() saves the changes permanently to the database, while rollback() undoes changes if an error occurs.
How can you check how many records were affected by DELETE?
Use cursor.rowcount property to get the number of rows affected by the last execute() operation.
What happens if you try to delete a record that doesn't exist?
No error occurs, but cursor.rowcount will return 0, indicating no records were affected.