Q:

Python program to search product records based on given price range from the database

belongs to collection: Python Database (SQL/MySQL) Programs

0

Program to search record from the database using price in Python.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

Algorithm:

  • Step 1: Connect to database using connect() method in pymysql.
  • Step 2: Get input of price range (maximum salary and minimum salary) from the user.
  • Step 3: Create a query to fetch records of products with price within a given price range.
  • Step 4: Execute the query and print the results.

Program to search a record by price

import pymysql as MYSQL

try:
    conn=MYSQL.connect(host='localhost',port=3306,
    user='root',password='123',db='practice')
    
    cmd=conn.cursor()
    
    min=input("Enter Min Price?")
    max = input("Enter Max Price?")
    
    q="select * from products where productrate between {} and {}".format(min,max)
    cmd.execute(q)
    
    rows=cmd.fetchall()
    
    if(rows==None):
        print("Record Not Found...")
    else:
        for row in rows:
            for cols in row:
                print(cols,end=' ')
        print()
    
    conn.close()
except Exception as e:
    print(e)

Output:

Enter Min Price?5000
Enter Max Price? 10000
04 EarPads 6299 2020
07 wireless Charger 9999 2021

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python program to update records in the database... >>
<< Python program to search for a record using ID in ...