Library Management System (Improved MySQL Version)
import [Link]
db = [Link](
host="localhost",
user="root",
password="12345678",
database="library")
cur = [Link]()
def add_book():
try:
id = int(input("Enter Book ID: "))
title = input("Enter Book Title: ")
author = input("Enter Author: ")
qty = int(input("Enter Quantity: "))
[Link]("INSERT INTO books VALUES (%s, %s, %s, %s)", (id, title,
author, qty))
[Link]()
print(" Book added!\n")
except Exception as e:
print(" Error adding book:", e, "\n")
def view_books():
[Link]("SELECT * FROM books")
data = [Link]()
if not data:
print(" No books found.\n")
else:
for b in data:
print(f"ID:{b[0]} | {b[1]} by {b[2]} | Qty:{b[3]}")
print()
def search_book():
name = input("Enter title or author to search: ")
[Link]("SELECT * FROM books WHERE title LIKE %s OR author LIKE %s", (f"%
{name}%", f"%{name}%"))
data = [Link]()
if not data:
print("No matching books found.\n")
else:
for b in data:
print(f"ID:{b[0]} | {b[1]} by {b[2]} | Qty:{b[3]}")
print()
def update_book():
try:
id = int(input("Enter Book ID to update: "))
qty = int(input("Enter new quantity: "))
[Link]("UPDATE books SET qty=%s WHERE id=%s", (qty, id))
[Link]()
if [Link] == 0:
print("No book found with that ID.\n")
else:
print(" Quantity updated!\n")
except Exception as e:
print("Error updating book:", e, "\n")
def delete_book():
try:
id = int(input("Enter Book ID to delete: "))
[Link]("DELETE FROM books WHERE id=%s", (id,))
[Link]()
if [Link] == 0:
print(" No book found with that ID.\n")
else:
print("Book deleted!\n")
except Exception as e:
print(" Error deleting book:", e, "\n")
while True:
print("""
LIBRARY MENU
1. Add Book
2. View Books
3. Search Book
4. Update Quantity
5. Delete Book
6. Exit
""")
ch = input("Enter choice: ")
if ch == '1':
add_book()
elif ch == '2':
view_books()
elif ch == '3':
search_book()
elif ch == '4':
update_book()
elif ch == '5':
delete_book()
elif ch == '6':
print("Thank you! Exiting Library System...")
break
else:
print(" Invalid choice. Try again.\n")