Test Index
CBSE Class 12 Computer Science 2025 Paper Compartment
© examsnet.com
Question : 35 of 37
Marks:
+1,
-0
Nutan Kumar is using Python connectivity with MySQL for maintaining data for a table named MEDICINES in a database PHARMACY. The table has the following attributes :•
MId (Medicine number) – string• Mname (Medicine Name) – string• Expiry (Expiry Date) – Date• Status (Active/Discard) – stringConsider the following to establish connectivity between Python and MySQL :• Username – root• Password – tiger• Host – localhostHelp Nutan to write the definition of a user-defined function named ChangeStatus() in Python to change the Status of the Medicines whose Expiry is before '2022-12-31' as 'DISCARD'.
Solution:
Concept: Steps of Python–MySQL connectivity: import
mysql.connector, connect with host, user, password and database, create a cursor, run the SQL with execute(), call commit() because UPDATE changes the table, then close the connection.import mysql.connector as mycondef ChangeStatus(): # connect to the PHARMACY database con = mycon.connect(host="localhost", user="root", passwd="tiger", database="PHARMACY") cur = con.cursor() query = "UPDATE MEDICINES SET Status = 'DISCARD' WHERE Expiry < '2022-12-31'" cur.execute(query) con.commit() # save the change permanently print(cur.rowcount, "record(s) updated") con.close()ChangeStatus()Key point: Without
con.commit() the UPDATE is not saved in the database. Dates in the form 'YYYY-MM-DD' compare correctly, so Expiry < '2022-12-31' selects medicines that expired before 31 December 2022.© examsnet.com
Go to Question: