Py 11
Py 11
Program:
import mysql.connector
def connect_to_database():
conn = mysql.connector.connect(host="localhost", user="root", password="",
database="library")
return conn
def create_database():
conn = connect_to_database()
cursor = conn.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS library")
conn.database = "library"
cursor.execute("CREATE TABLE IF NOT EXISTS books (title VARCHAR(255), author
VARCHAR(255), price DECIMAL(10, 2))")
num_books = int(input("Enter the number of books: "))
for _ in range(num_books):
name_book = input("Enter the name of the book: ")
name_author = input("Enter the name of the author: ")
price_book = input("Enter the price of the book: ")
print("Book added successfully.")
cursor.execute("INSERT INTO books (title, author, price) VALUES (%s, %s, %s)",
(name_book, name_author, price_book))
conn.commit()
conn.close()
def show_book_details():
conn = connect_to_database()
cursor = conn.cursor()
cursor.execute("SELECT title, author, price FROM books")
books = cursor.fetchall()
for book in books:
title, author, price = book
print(f'Title: {title}\nAuthor: {author}\nPrice: {price}\n')
def calculate_total(title, quantity):
conn = connect_to_database()
cursor = conn.cursor()
cursor.execute("SELECT price FROM books WHERE title=%s", (title,))
result = cursor.fetchone()
if result:
price = result[0]
total_amount = price * quantity
print(f'Total amount for {quantity} copies of "{title}": {total_amount:.2f}')
else:
print(f'Book with title "{title}" not found in the database.')
conn.close()
if __name__ == "__main__":
create_database()
show_book_details()
title = input("Enter the title of the book: ")
quantity = int(input("Enter the quantity purchased: "))
calculate_total(title, quantity)
************************************B444**********************************
Output:
Conclusion :
I learned that establishing connections with database facilitates an efficient way to perform
tasks such as data retrieval, insertion, and manipulation.