Q.A table, named THEATRE, in CINEMA database, has the following structure : Fields Type Th_ID char(5) Name varchar(15) City varchar(15) Location varchar(15) Seats int Write a function Delete_Theatre(), to input the value of Th_ID from the user and permanently delete the corresponding record from the table. Assume the following for Python-Database connectivity : Host : localhost, User : root, Password : Ex2025
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →This solution provides a Python function Delete_Theatre() that connects to a MySQL database, prompts the user for a Th_ID, and then executes an SQL DELETE statement to permanently remove the corresponding record from the THEATRE table.
When you need to interact with a database from a Python program, you essentially need a translator. Python speaks Python, and MySQL speaks SQL. A database connector library acts as this translator, allowing your Python code to send SQL commands to the database and receive results. For MySQL, the mysql.connector library is the standard choice.
The core idea here is to:
- Connect to the MySQL database using the provided credentials.
- Obtain input from the user for the
Th_IDof the record to be deleted. - Construct an SQL
DELETEstatement that specifically targets the record with the givenTh_ID. TheWHEREclause is critical here, as it prevents accidental deletion of all records. - Execute this SQL statement.
- Commit the transaction to make the deletion permanent. Without committing, the changes would only be temporary and would be rolled back.
- Close the connection to release database resources.
Let's break down the implementation step-by-step.
-
Import the
mysql.connectorlibraryThis is the first step to enable Python to communicate with MySQL. If you haven't installed it, you would typically do so using
pip install mysql-connector-python.import mysql.connector -
Define the
Delete_Theatre()functionWe encapsulate the logic within a function as requested.
def Delete_Theatre(): # ... function body ... -
Get
Th_IDfrom the userThe function needs to know which theatre record to delete. We use
input()to prompt the user for theTh_ID. SinceTh_IDischar(5), it's a string.th_id_to_delete = input("Enter the Theatre ID (Th_ID) of the record to delete: ").strip() if not th_id_to_delete: print("Theatre ID cannot be empty. Deletion cancelled.") returnTipUsing
.strip()removes any leading or trailing whitespace from the user's input, which can prevent issues if the user accidentally types a space. -
Establish a database connection
We use
mysql.connector.connect()to establish a connection. The problem specifies the host, user, and password. The database name is implied asCINEMAfrom the problem description "in CINEMA database". It's good practice to wrap this in atry-exceptblock to handle potential connection errors (e.g., wrong credentials, database server not running).mydb = None # Initialize to None try: mydb = mysql.connector.connect( host="localhost", user="root", password="Ex2025", database="CINEMA" # As specified in the problem context ) print("Successfully connected to the CINEMA database.") except mysql.connector.Error as err: print(f"Error connecting to MySQL database: {err}") return # Exit the function if connection fails -
Create a cursor object
Once connected, you need a cursor object to execute SQL queries. Think of the cursor as the interface through which you send commands to the database.
mycursor = mydb.cursor() -
Construct the
DELETESQL queryThe SQL
DELETEstatement is used to remove rows from a table. TheWHEREclause is crucial to specify which rows to delete. Without aWHEREclause, all rows would be deleted, which is almost never the intention. We use a parameterized query (%s) for safety and to prevent SQL injection vulnerabilities.sql_query = "DELETE FROM THEATRE WHERE Th_ID = %s" val = (th_id_to_delete,) # The value must be a tuple, even for a single parameterWatch outNever concatenate user input directly into an SQL query string (e.g.,
f"DELETE FROM THEATRE WHERE Th_ID = '{th_id_to_delete}'"). This is a major security risk known as SQL injection. Always use parameterized queries where the database connector handles the proper escaping of values. -
Execute the query and commit changes
The
mycursor.execute()method runs the SQL query. After executing a data modification query (likeDELETE,INSERT,UPDATE), you must callmydb.commit()to save the changes permanently to the database. If you don't commit, the changes will be rolled back when the connection is closed.try: mycursor.execute(sql_query, val) mydb.commit() # Make the changes permanent print(f"{mycursor.rowcount} record(s) deleted successfully.") if mycursor.rowcount == 0: print(f"No record found with Th_ID: '{th_id_to_delete}'.") except mysql.connector.Error as err: print(f"Error deleting record: {err}") mydb.rollback() # Rollback changes if an error occursImportantmydb.commit()is essential forDELETE,INSERT,UPDATEoperations. Without it, your changes will not be saved.mycursor.rowcountis a useful attribute that tells you how many rows were affected by the last executed query. -
Close cursor and connection
It's good practice to close the cursor and the database connection when you are done with them to free up resources. This should ideally happen in a
finallyblock to ensure they are closed even if errors occur.finally: …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.