Question:hard

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

Solution and Explanation

Step 1: Work out what the program must do:
There are five jobs in order: connect, make a cursor, run a query, read the rows, close.
The query itself is the heart of the answer. It is SELECT * FROM Account WHERE Fees < 5000.
The star picks Stud_id, Sname, Class and Fees. The WHERE part keeps only fees below 5000.

Step 2: Write the connection line:
The call mysql.connector.connect() needs the four values from the note.
The host is localhost, the user is admin and the password is root. The database is SCHOOL.
The module name is imported first, or the call fails with a NameError.

Step 3: Read the result one record at a time:
Here we use fetchone() inside a while loop. It returns the next record, and None when no rows are left.
This style suits a big table, because only one record is held in memory at a time.
Fetchall() would work as well, and many students use it.

Step 4: Put the program together:
import mysql.connector

mydb = mysql.connector.connect(host='localhost', user='admin', password='root', database='SCHOOL')
if mydb.is_connected():
    mycur = mydb.cursor()
    mycur.execute('SELECT * FROM Account WHERE Fees < 5000')
    rec = mycur.fetchone()
    while rec is not None:
        print(rec)
        rec = mycur.fetchone()
mydb.close()


Step 5: Check the flow:
If the login is wrong, connect() raises an error and nothing is printed.
If no student pays below 5000, the first fetchone() gives None and the loop never runs.

Final Answer:
The code above displays all records of the Account table where Fees is less than 5000.
Was this answer helpful?
0