×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

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

Here, we will write a Python program that will display all products from the database table whose price lies within the given range.
Submitted by Shivang Yadav, on February 21, 2021

Problem Statement: Program to search record from the database using price 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.

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

Python database (SQL/MySQL) programs »



Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.