HomeComputer SciencePracticalClass 12Delete Records

Class 12 Programs

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

  1. Start
  2. Import mysql.connector module
  3. Establish connection to MySQL database
  4. Create cursor object
  5. Display all records before deletion
  6. Accept condition for deletion from user
  7. Execute DELETE query with WHERE clause
  8. Commit the transaction
  9. Display confirmation message
  10. Display remaining records after deletion
  11. Close cursor and connection
  12. 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

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.