Computer Science

A table, named STATIONERY, in ITEMDB database, has the following structure:

FieldType
itemNoint(11)
itemNamevarchar(15)
pricefloat
qtyint(11)

Write the following Python function to perform the specified operation:

AddAndDisplay(): To input details of an item and store it in the table STATIONERY. The function should then retrieve and display all records from the STATIONERY table where the Price is greater than 120.

Assume the following for Python-Database connectivity:

Host: localhost, User: root, Password: Pencil

Python MySQL

15 Likes

Answer

import mysql.connector

def AddAndDisplay():
    db = mysql.connector.connect(
            host="localhost",
            user="root",
            password="Pencil",
            database="ITEMDB"
        )
    cursor = db.cursor()
    item_no = int(input("Enter Item Number: "))
    item_name = input("Enter Item Name: ")
    price = float(input("Enter Price: "))
    qty = int(input("Enter Quantity: "))
    insert_query = "INSERT INTO STATIONERY VALUES ({}, {}, {}, {})"
    insert_query = insert_query.format(item_no, item_name, price, qty)
    cursor.execute(insert_query)
    db.commit()
    select_query = "SELECT * FROM STATIONERY WHERE price > 120"
    cursor.execute(select_query)
    results = cursor.fetchall()
    for record in results:
        print(record)
            
AddAndDisplay()

Answered By

11 Likes


Related Questions