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 TUPLE
AIM
To write a Python program to interface with MySQL database and delete specific tuples (rows) from a table based on user-defined conditions.
ALGORITHM
- Start
- Import mysql.connector module
- Establish connection to MySQL database
- Create cursor object
- Display all tuples before deletion
- Accept deletion criteria from user
- Construct DELETE query with appropriate WHERE clause
- Execute the DELETE statement
- Commit the transaction
- Display number of tuples deleted
- Display remaining tuples after deletion
- Close cursor and connection
- Stop
PROGRAM
# Python program to delete tuples from MySQL database
import mysql.connector
def connect_database():
"""Establish connection to MySQL database"""
try:
connection = mysql.connector.connect(
host='localhost',
database='company',
user='root',
password='password'
)
return connection
except mysql.connector.Error as error:
print(f"Error connecting to MySQL: {error}")
return None
def display_employees(cursor):
"""Display all employee tuples"""
cursor.execute("SELECT * FROM employees")
records = cursor.fetchall()
if records:
print("\n--- Employee Records ---")
print("EmpID\tName\t\tDept\t\tSalary")
print("-" * 50)
for record in records:
print(f"{record[0]}\t{record[1]:<12}\t{record[2]:<12}\t{record[3]}")
else:
print("No employee records found.")
def delete_tuples():
"""Main function to delete tuples"""
connection = connect_database()
if connection is None:
return
cursor = connection.cursor()
try:
# Display all tuples before deletion
print("Employee records before deletion:")
display_employees(cursor)
# Get deletion criteria
print("\nDelete employees based on:")
print("1. Employee ID")
print("2. Department")
print("3. Salary range")
print("4. Name")
choice = input("Enter your choice (1-4): ")
if choice == '1':
emp_id = input("Enter Employee ID to delete: ")
query = "DELETE FROM employees WHERE emp_id = %s"
values = (emp_id,)
elif choice == '2':
dept = input("Enter Department name: ")
query = "DELETE FROM employees WHERE department = %s"
values = (dept,)
elif choice == '3':
min_salary = input("Enter minimum salary: ")
max_salary = input("Enter maximum salary: ")
query = "DELETE FROM employees WHERE salary BETWEEN %s AND %s"
values = (min_salary, max_salary)
elif choice == '4':
name = input("Enter employee name: ")
query = "DELETE FROM employees WHERE name = %s"
values = (name,)
else:
print("Invalid choice!")
return
# Confirm deletion
confirm = input(f"\nAre you sure you want to delete? (y/n): ")
if confirm.lower() != 'y':
print("Deletion cancelled.")
return
# Execute delete query
cursor.execute(query, values)
if cursor.rowcount > 0:
connection.commit()
print(f"\n{cursor.rowcount} tuple(s) deleted successfully!")
# Display remaining tuples
print("\nEmployee records after deletion:")
display_employees(cursor)
else:
print("No tuples found matching the criteria.")
except mysql.connector.Error as error:
print(f"Error deleting tuples: {error}")
connection.rollback()
finally:
cursor.close()
connection.close()
print("\nDatabase connection closed.")
def create_sample_data():
"""Create sample employee data for demonstration"""
connection = connect_database()
if connection is None:
return
cursor = connection.cursor()
try:
# Create table if not exists
cursor.execute("""
CREATE TABLE IF NOT EXISTS employees (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
department VARCHAR(30),
salary DECIMAL(10,2)
)
""")
# Insert sample data
sample_data = [
(101, 'John Smith', 'IT', 75000.00),
(102, 'Jane Doe', 'HR', 65000.00),
(103, 'Mike Johnson', 'IT', 80000.00),
(104, 'Sarah Wilson', 'Finance', 70000.00),
(105, 'Bob Brown', 'IT', 72000.00)
]
cursor.executemany(
"INSERT IGNORE INTO employees VALUES (%s, %s, %s, %s)",
sample_data
)
connection.commit()
print("Sample employee data created!")
except mysql.connector.Error as error:
print(f"Error creating sample data: {error}")
finally:
cursor.close()
connection.close()
# Main program
if __name__ == "__main__":
print("=== MySQL Database - Delete Tuples ===")
# Create sample data first
create_sample_data()
# Perform delete operations
delete_tuples()OUTPUT
=== MySQL Database - Delete Tuples ===
Sample employee data created!
Employee records before deletion:
--- Employee Records ---
EmpID Name Dept Salary
--------------------------------------------------
101 John Smith IT 75000.0
102 Jane Doe HR 65000.0
103 Mike Johnson IT 80000.0
104 Sarah Wilson Finance 70000.0
105 Bob Brown IT 72000.0
Delete employees based on:
1. Employee ID
2. Department
3. Salary range
4. Name
Enter your choice (1-4): 2
Enter Department name: IT
Are you sure you want to delete? (y/n): y
3 tuple(s) deleted successfully!
Employee records after deletion:
--- Employee Records ---
EmpID Name Dept Salary
--------------------------------------------------
102 Jane Doe HR 65000.0
104 Sarah Wilson Finance 70000.0
Database connection closed.
CONCLUSION
The program successfully demonstrates how to delete specific tuples from a MySQL database using Python. It provides multiple deletion criteria options, includes confirmation prompts for safety, and shows proper transaction management with commit/rollback functionality.
VIVA QUESTIONS
What is a tuple in the context of databases?
A tuple is a single row in a database table, containing a set of related data values across multiple columns.
Why is it important to confirm before deleting tuples?
Deletion is irreversible, so confirmation prevents accidental data loss and ensures user intent.
What is the BETWEEN operator used for?
BETWEEN is used to select values within a given range, inclusive of both boundary values.
How does executemany() differ from execute()?
executemany() executes the same query multiple times with different parameter sets, while execute() runs a single query.
What does INSERT IGNORE do?
INSERT IGNORE prevents errors when trying to insert duplicate primary key values, silently skipping such insertions.