Question:

Peter has created a table named Account in MySQL database, SCHOOL, having following structure:

Stud_id – integer
Sname – string
Class – string
Fees – float

Help him in writing a Python program to display records of those students whose fees is less than 5000.

Note the following to establish connectivity between Python and MySQL: Username – admin, Password – root, Host – localhost

Show Hint

Import mysql.connector, connect with the given login, execute SELECT * FROM Account WHERE Fees < 5000, fetch the rows and print them.
Updated On: Oct 20, 2026
Show Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Step 1: Import the connector module:
Python talks to MySQL through the module mysql.connector.
We import it with a short name so the code stays easy to read.

Step 2: Connect to the database:
The function connect() takes the host, user, password and database name.
From the question these values are host = localhost, user = admin, password = root and database = SCHOOL.
It returns a connection object.

Step 3: Create a cursor and run the query:
A cursor object is made from the connection with cursor().
The method execute() sends an SQL statement to MySQL.
The records with fees below 5000 are selected with WHERE Fees < 5000.
The table name is Account, as given.

Step 4: Fetch and display the records:
The method fetchall() brings all matching rows as a list of tuples.
A for loop prints one tuple per student.

Step 5: Close the connection:
The last line closes the connection, so the resources are freed.

Complete program:
import mysql.connector as mc

con = mc.connect(host='localhost', user='admin', password='root', database='SCHOOL')
cur = con.cursor()
cur.execute('SELECT * FROM Account WHERE Fees < 5000')
data = cur.fetchall()
for row in data:
    print(row)
con.close()


Final Answer:
The program connects with the given login, runs SELECT * FROM Account WHERE Fees < 5000, and prints every returned record as a tuple of (Stud_id, Sname, Class, Fees).
Was this answer helpful?
0
0