Home »
Python »
Python Programs
Select Employees Records Whose Salary is within the Given Range in Python
Python MySQL | Select Employees Records: In this tutorial, we will learn how to select and print the records of all those employees whose salary is within the given range with the help of Python program?
By Shivang Yadav Last updated : April 21, 2023
Problem Statement
We need to fetch the details of employees from the database whose salaries are within a certain range in Python.
Solution
We will use python's pymysql library to work with the database. This library provides the programmer the functionality to run MySQL query using Python.
The following steps can be used to get the employees records based on the salary condition:
- Take the maximum and minimum salary from the user.
- Create a MySQL query, to select data within the range from the database. Refer: SQL tutorial for help.
- Connect to database and run the query. Using the execute command.
- Store all fetched employee details in row variable.
- Print details.
Python Program to Select Employees Records Whose Salary is within the Given Range
import pymysql as mysql
try:
conn=mysql.connect(host='localhost',port=3306,user='root',password='123',db='myschool')
cmd=conn.cursor()
min=input("Enter Min Salary : ")
max=input("Enter Max Salary : ")
q="select * from faculties where salary between {} and {}".format(min,max)
cmd.execute(q)
rows=cmd.fetchall()
#print(rows)
for row in rows:
print(row[1],row[4])
conn.close()
except Exception as e:
print("Error:",e)
Output
Enter Min Salary : 25000
Enter Max Salary : 45000
34 34000
65 29500
Python MySQL Programs »