0% found this document useful (0 votes)
4 views

Yugank library code

Uploaded by

abhij7262
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Yugank library code

Uploaded by

abhij7262
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

# Importing necessary libraries

import mysql.connector
import pyfiglet
import requests
import wikipediaapi
from datetime import datetime, timedelta

# Connect to the MySQL database


db = mysql.connector.connect(
host="localhost",
user="root",
password="admin",
database="library",
)
c = db.cursor()

# Function to display the return policy information


def returnPolicy():
print("Return Policy :")
print("The issued book should be returned within 14 days (2 weeks).")
print(
"If the user kept the issued book for more than 14 days, then the user has
to pay ₹5 as a fine for each extra day the user kept the issued book."
)
print("-----------------------")

# Function to calculate the length of a given integer after converting it to a


string
def length(i):
s = str(i)
length = len(s) + 2
return length

# Function to display a message for an invalid option


def validOption():
print("Please enter a valid option!")
print("-----------------------")

# Function to handle program exit


def exiting():
print("\033[3;34m-----------------------\033[0;0m")
print("\033[3;33mExiting the program.")
print("Thank You!\033[0;0m")
print("\033[3;34m-----------------------\033[0;0m")
exit()

# Function to display the user menu and handle user choices


def userMenu():
# Displaying options for the user
print("1. Add Note")
print("2. Home")
print("3. Back")
print("4. Exit")

# Taking user choice as input


userChoice = int(input("Enter your Choice to Continue : "))
print("-----------------------")

# Handle user choices


if userChoice == 1:
addNote()
elif userChoice == 2:
home()
elif userChoice == 3:
back()
elif userChoice == 4:
exiting()
else:
validOption()

# Function to display information about the library


def aboutLibrary():
# Retrieve the name of the librarian who is also an admin
c.execute("SELECT userName FROM users WHERE adminStatus='admin'")
userName = c.fetchall()

# Retrieve the total number of books and users in the library


c.execute("SELECT * FROM books")
totalBooks = c.fetchall()

c.execute("SELECT * FROM users")


totalUsers = c.fetchall()
db.commit()

print("-----------------------")
print("About Library")
print("-----------------------")
# Display library information
print("Year of Library's Establishment :", 2023)
print("Name of the Librarian :", userName[0][0])
print("Total Number of Books Available in the Library :", len(totalBooks))
print("Total Number of Users Enrolled in the Library :", len(totalUsers))
print("-----------------------")
userMenu()

# Function to display the list of books in the library


def displayBooks():
print("-----------------------")
print("Display Books")
print("-----------------------")

# Retrieve all books from the database


c.execute("SELECT * FROM books ORDER BY bookId")
result = c.fetchall()
db.commit()

# Display books if available, otherwise notify the user


if result:
print("Books available in the Digital Library are:")
print("-----------------------")
i = 0
for row in result:
i += 1
r = length(i)
print(f"{i}. Book ID : {row[0]}")
print(f"{r * ' '}Book Name : {row[1]}")
print(f"{r * ' '}Publication Year : {row[2]}")
print(f"{r * ' '}Author Name : {row[7]}")
print(f"{r * ' '}Issue Status : {row[8]}")
print("-----------------------")
userMenu()
else:
print("No books found.")
print("-----------------------")
userMenu()

# Function to add a new user to the library database


def addUser():
print("-----------------------")
print("Add New User")
print("-----------------------")
userName = input("Enter User Name: ")
userEmail = input("Enter User Email: ")
userPhone = input("Enter User Phone Number: ")
userAddress = input("Enter User Address: ")

try:
c.execute(
"INSERT INTO users (userName, userEmail, userPhone, userAddress) VALUES
(%s, %s, %s, %s)",
(userName, userEmail, userPhone, userAddress),
)
db.commit()
print("User added successfully!")
except Exception as e:
print(f"Error: {e}")
print("-----------------------")
userMenu()

# Function to add a new book to the library database


def addBook():
print("-----------------------")
print("Add New Book")
print("-----------------------")
bookName = input("Enter Book Name: ")
bookAuthor = input("Enter Book Author: ")
bookYear = int(input("Enter Publication Year: "))
bookGenre = input("Enter Book Genre: ")

try:
c.execute(
"INSERT INTO books (bookName, bookAuthor, bookYear, bookGenre) VALUES
(%s, %s, %s, %s)",
(bookName, bookAuthor, bookYear, bookGenre),
)
db.commit()
print("Book added successfully!")
except Exception as e:
print(f"Error: {e}")
print("-----------------------")
userMenu()

# Function to issue a book to a user


def issueBook():
print("-----------------------")
print("Issue Book")
print("-----------------------")
userId = int(input("Enter User ID: "))
bookId = int(input("Enter Book ID: "))

try:
# Check if the book is available
c.execute("SELECT issueStatus FROM books WHERE bookId=%s", (bookId,))
book = c.fetchone()
if book and book[0] == "Available":
c.execute(
"INSERT INTO issuedBooks (userId, bookId, issueDate) VALUES (%s,
%s, %s)",
(userId, bookId, datetime.now()),
)
c.execute(
"UPDATE books SET issueStatus='Issued' WHERE bookId=%s", (bookId,)
)
db.commit()
print("Book issued successfully!")
else:
print("Book is not available for issuing.")
except Exception as e:
print(f"Error: {e}")
print("-----------------------")
userMenu()

# Function to return an issued book


def returnBook():
print("-----------------------")
print("Return Book")
print("-----------------------")
issueId = int(input("Enter Issue ID: "))

try:
# Retrieve issue details
c.execute(
"SELECT bookId, issueDate FROM issuedBooks WHERE issueId=%s",
(issueId,)
)
issue = c.fetchone()

if issue:
bookId, issueDate = issue
returnDate = datetime.now()
daysIssued = (returnDate - issueDate).days

# Calculate fine if applicable


fine = max(0, daysIssued - 14) * 5

# Update records
c.execute(
"DELETE FROM issuedBooks WHERE issueId=%s", (issueId,)
)
c.execute(
"UPDATE books SET issueStatus='Available' WHERE bookId=%s",
(bookId,)
)
db.commit()

print(f"Book returned successfully! Fine: ₹{fine}")


else:
print("No record found for the provided Issue ID.")
except Exception as e:
print(f"Error: {e}")
print("-----------------------")
userMenu()

# Function to search books by genre


def searchBooksByGenre():
print("-----------------------")
print("Search Books by Genre")
print("-----------------------")
genre = input("Enter Genre to Search: ")

try:
c.execute("SELECT * FROM books WHERE bookGenre LIKE %s", ("%" + genre +
"%",))
results = c.fetchall()

if results:
for row in results:
print(f"Book ID: {row[0]}, Name: {row[1]}, Author: {row[7]}")
print("-----------------------")
else:
print("No books found for the given genre.")
except Exception as e:
print(f"Error: {e}")
print("-----------------------")
userMenu()

# Function to recommend books based on user borrowing history


def recommendBooks(userId):
print("-----------------------")
print("Book Recommendations")
print("-----------------------")

try:
# Retrieve genres of previously borrowed books
c.execute(
"SELECT DISTINCT bookGenre FROM books WHERE bookId IN (SELECT bookId
FROM issuedBooks WHERE userId = %s)",
(userId,),
)
genres = c.fetchall()

if genres:
for genre in genres:
c.execute("SELECT * FROM books WHERE bookGenre = %s LIMIT 3",
(genre[0],))
recommendations = c.fetchall()

print(f"Recommended Books in {genre[0]}:")


for book in recommendations:
print(f"Book ID: {book[0]}, Name: {book[1]}")
print("-----------------------")
else:
print("No recommendations available.")
except Exception as e:
print(f"Error: {e}")
print("-----------------------")
userMenu()

# Function to view borrowed books by a specific user


def viewBorrowedBooks(userId):
print("-----------------------")
print(f"Borrowed Books for User ID {userId}")
print("-----------------------")

try:
c.execute(
"SELECT b.bookName, b.bookAuthor, i.issueDate FROM books b JOIN
issuedBooks i ON b.bookId = i.bookId WHERE i.userId = %s",
(userId,),
)
borrowedBooks = c.fetchall()

if borrowedBooks:
for book in borrowedBooks:
print(f"Book Name: {book[0]}, Author: {book[1]}, Issued On:
{book[2]}")
print("-----------------------")
else:
print("No borrowed books found.")
except Exception as e:
print(f"Error: {e}")
print("-----------------------")
userMenu()

# Main Function
def main():
print(pyfiglet.figlet_format("Library Management System"))
userMenu()

# Run the program


if __name__ == "__main__":
main()

You might also like