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

code

The document is a Python script for a Library Management System that allows users to manage books and issue records in a MySQL database. It includes functions for adding, updating, deleting, and searching for books, as well as managing issue records for borrowers. The script also handles user input and exceptions, ensuring that operations are performed correctly and providing feedback to the user.

Uploaded by

Mishita Gogia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

code

The document is a Python script for a Library Management System that allows users to manage books and issue records in a MySQL database. It includes functions for adding, updating, deleting, and searching for books, as well as managing issue records for borrowers. The script also handles user input and exceptions, ensuring that operations are performed correctly and providing feedback to the user.

Uploaded by

Mishita Gogia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

CODE

import mysql.connector as ms

#defining all functions

#adding books to the Books Table

def addbk():

while True:

try:

b_id=int(input(“Enter unique Book ID : ”))

b_name=input(“Enter the name of the book : ”)

b_auth=input(“Enter the name of the author : ”)

b_genre=input(“Enter the genre of the book : ”)

b_copies=int(input(“Enter the number of copies of the book : ”))

add=”INSERT INTO Books values({},’{}’.’{}’,’{}’,


{})”.format(b_id,b_name,b_auth,b_genre,b_copies)

cur.execute()

db.commit()

print("The records have been successfully updated.")

print()

check=input('More books? Y/N: ')

if check.lower()=='y':

pass

else:

print('N or other value entered, addition of records terminated.')

break

print()

except:
print('An unexpected error occurred, please try again')
db.rollback()

print()

break

#changing number of copies

def change():

try:

b_id=int(input("Enter ID of the book you want to change copies for: "))

n=int(input("Enter the number of copies available: "))

change="UPDATE Books SET b_copies={} WHERE B_id={};".format(n,b_id)

cur.execute(change)

print("The copies have been successfully updated.")

db.commit()

print()

except:

print('An unexpected error occurred, please try again')

db.rollback()

print()

#deleting records from book table

def delbook():

try:

b_id=int(input("Enter ID of the book you want to delete: "))

d="DELETE FROM Books WHERE B_Id={};".format(b_id)

cur.execute(d)

print("The record has been successfully deleted.")


db.commit()

print()

except:

print('An unexpected error occurred, please try again')

db.rollback()

print()

#searching for book records

def search():

try:

param=int(input(''Using which parameter would you like to search for the


book records?:

1. BookId

2. Book name

Please input choices 1/2: '' ))

if param==1:

bkid=int(input("Enter the BookId: "))

sql3="SELECT * FROM Books WHERE B_id={};".format(bkid)

cur.execute(sql3)

res3=cur.fetchall()

print("The book by the BookId",bkid,"is: ",res3)

print()

elif param==2:

bkname=input("Enter the name of the book: ")

sql4="SELECT * FROM Books WHERE B_name='{}';".format(bkname)


cur.execute(sql4)

res4=cur.fetchall()

print("The book(s) by the name",bkname,"is/are: ")


for i in res4:

print(i)

print()

else:

print("Invalid input, kindly enter 1 or 2")

print()

except:

print('An unexpected error occurred, please try again')

print()

#viewing all book records

def viewallbooks():

try:

sel='SELECT * FROM Books'

cur.execute(sel)

res=cur.fetchall()

print('The book records are: ')

for i in res:

print(i)

print()

except:

print('An unexpected error occurred, please try again')

print()

#viewing all books for a particular author

def author():

try:
bkauth=input("Enter the author whose books you want to view: ")

sql2="SELECT * FROM Books WHERE B_author='{}';".format(bkauth)

cur.execute(sql2)

res2=cur.fetchall()

print("The books by",bkauth,"are: ")

for i in res2:

print(i)

print()

except:

print('An unexpected error occurred, please try again')

print()

#viewing all books of a particular genre

def genre():

try:

bkgen=input("Enter the genre you want to search for: ")

sql1="SELECT * FROM Books WHERE B_genre='{}';".format(bkgen)

cur.execute(sql1)

res1=cur.fetchall()

print("The books for the genre",bkgen,"are: ")

for i in res1:

print(i)

print()

except:

print('An unexpected error occurred, please try again')

print()
#Adding issue records

def addrec():

while True:

try:

iss_id=int(input("Enter issuer's ID: "))

name=input("Enter issuer's name: ")

category=input("Enter category (S/T): ").upper()

B_id=int(input("Enter ID of the book issued: "))

date=input("Enter date of issue (YYYY-MM-DD): ")

ch='SELECT B_copies from Books where B_id={}'.format(B_id)

cur.execute(ch)

res=cur.fetchone()

if res[0]>0:

add="INSERT INTO issue_records VALUES ({},'{}','{}',


{},'{}')".format(iss_id,name,category,B_id,date)

cur.execute(add)

db.commit()

reduce='UPDATE Books SET B_copies=B_copies-1 WHERE B_id=


{}'.format(B_id)

cur.execute(reduce)

db.commit()

print("The records have been successfully updated.")

print()

else:

print('Number of copies for this book is 0, please wait till the


previous issuer returns the book')

print()

check=input('More IDs? Y/N: ')


if check.lower()=='y':

pass

else:

print('N or other value entered, addition of records terminated')

break

print()

except:

print('An unexpected error occurred, please try again')

db.rollback()

print()

#Delete issue records

def delissue():

try:

d_id=int(input("Enter issuer's ID: "))

dell='DELETE FROM issue_records WHERE I_id={}'.format(d_id)

cur.execute(dell)

db.commit()

B_id=int(input('Enter the ID of the returned book: '))

inc='UPDATE Books SET B_copies=B_copies+1 WHERE B_id={}'.format(B_id)

cur.execute(inc)

db.commit()

print('record successfully deleted')

print()

except:

print('An unexpected error occurred, please try again')

db.rollback()
print()

#view all issue records

def viewallissues():

try:

show='SELECT * FROM issue_records'

cur.execute(show)

result=cur.fetchall()

print('The issue records are: ')

for i in result:

print(i)

print()

except:

print('An unexpected error occurred, please try again')

print()

#checking issuer records for a particular issuer

def checkrecords():

try:

print(''Would you like to search for the issuer via:

1. Issue ID

2. Name of issuer'')

check=int(input('Enter the corresponding number to search: '))

if check==1:

idd=int(input("Enter issuer's ID: "))

run="SELECT * FROM issue_records WHERE I_id={}".format(idd)


cur.execute(run)
res=cur.fetchall()

print('The issue record for this issue ID is:')

for i in res:

print(i)

print()

elif check==2:

name=input("Enter name of issuer: ")

run="SELECT * FROM issue_records WHERE name='{}'".format(name)

cur.execute(run)

res=cur.fetchall()

print('The issue record for this issue ID is:')

for i in res:

print(i)

print()

else:

print('invalid input')

print()

except:

print('An unexpected error occurred, please try again')

print()

#checking who all issued a particular book

def findwho():

try:

BID= int(input("Enter ID of the book to find issuers: "))

find="SELECT * FROM issue_records WHERE B_id={}".format(BID)

cur.execute(find)
r=cur.fetchall()

print("The records of people issuing this book are:-")

for i in r:

print(i)

print()

except:

print('An unexpected error occurred, please try again')

print()

#view issue records for all students/all teachers

def showselrec():

try:

check=input('Enter S for all student records, T for all teacher records:


').upper()

show='SELECT * FROM issue_records WHERE category="{}"'.format(check)

cur.execute(show)

r=cur.fetchall()

print('The selected records are: ')

for i in r:

print(i)

print()

except:

print('An unexpected error occurred, please try again')

print()

#viewing issuers on a particular date

def dateissue():
try:

print('The date should be entered in the YYYY-MM-DD format only')

date=input('Enter the date: ')

show='SELECT * FROM issue_records WHERE I_date="{}"'.format(date)

cur.execute(show)

r=cur.fetchall()

print('The records are:')

for i in r:

print(i)

print()

except:

print('An unexpected error occurred, please try again')

print()

#checking for return delay

def checkdelay():

try:

print("A book must be returned within 3 weeks of issuing else it'll have
to pay a return delay fine of 400 rupees")

print()

ID=int(input('Enter ID of the issuer you want to check for return delay:


'))

sql='select I_date from issue_records where I_id={}'.format(ID)

cur.execute(sql)

y=cur.fetchall()

print('The issue date is: ', str(y[0][0]))

date=str(y[0][0])

year=int(date[:4])
month=int(date[5:7])

day=int(date[8:])

#checking for leap year (1=yes and 0=no)

leap=0

if year%4==0 and year%100!=0:

leap=1

elif year%400==0:

leap=1

else:

leap=0

#checking for days in months

days=0

if date[5:7] in ['01','03','05','07','08','10','12']:

monthdays=31

elif date[5:7] in ['04','06','09','11']:

monthdays=30

elif date[5:7]=='02':

if leap==1:

monthdays=29

elif leap==0:

monthdays=28

else:

pass

#new date
if monthdays==31:

if day<11:

newday=day+21

if len(str(month))>1:

m=str(month)

else:

m='0'+str(month)

newdate=(str(year)+'-'+m+'-'+str(newday))

elif day>=11 and month==12:

newyear=year+1

newmonth='01'

newdate=day-10

if len(str(newdate))>1:

newdate=(str(newyear)+'-'+newmonth+'-'+str(newdate))

else:

newdate=(str(newyear)+'-'+newmonth+'-'+'0'+str(newdate))

elif day>=11 and month!=12:

newday2=day-10

if len(str(newday2))>1:

nd=str(newday2)

else:

nd='0'+str(newday2)

newmonth2=month+1

if len(str(newmonth2))>1:

nm=str(newmonth2)

else:

nm='0'+str(newmonth2)
newdate=(str(year)+'-'+nm+'-'+nd)

else:

pass

elif monthdays==30:

if day<10:

newday4=day+21

if len(str(month))>1:

m1=str(month)

else:

m1='0'+str(month)

newdate=(str(year)+'-'+m1+'-'+str(newday4))

elif day>=10:

newday5=day-9

if len(str(newday5))>1:

nd1=str(newday5)

else:

nd1='0'+str(newday5)

newmonth3=month+1

if len(str(newmonth3))>1:

nm1=str(newmonth3)

else:

nm1='0'+str(newmonth3)

newdate=(str(year)+'-'+nm1+'-'+nd1)

else:

pass

elif monthdays==29:

if day<9:
newday6=day+21

newdate=(str(year)+'-'+'02'+'-'+str(newday6))

elif day>=9:

newday7=day-8

if len(str(newday7))>1:

nd2=str(newday7)

else:

nd2='0'+str(newday7)

newmonth4=month+1

if len(str(newmonth4))>1:

nm2=str(newmonth4)

else:

nm2='0'+str(newmonth4)

newdate=(str(year)+'-'+nm2+'-'+nd2)

else:

pass

elif monthdays==28:

if day<8:

newday8=day+21

newdate=(str(year)+'-'+'02'+'-'+str(newday8))

elif day>=8:

newday9=day-7

if len(str(newday9))>1:

nd3=str(newday9)

else:

nd3='0'+str(newday9)

newmonth5=month+1
if len(str(newmonth5))>1:

nm3=str(newmonth5)

else:

nm3='0'+str(newmonth5)

newdate=(str(year)+'-'+nm3+'-'+nd3)

else:

pass

else:

pass

print('The predicted date of return is: ',newdate)

delay=0

run='select(date(now()))'

cur.execute(run)

r=cur.fetchall()

today=str(r[0][0])

print("Today's date is: ",today)

print()

if today < newdate:

delay=0

else:

delay=1

st='SELECT category FROM issue_records WHERE I_id={}'.format(ID)

cur.execute(st)

cat=cur.fetchone()
if delay==0:

print('No delay')

elif delay==1 and cat[0]=='T':

print('There is a return delay, but no fine because the issuer is a


teacher.')

elif delay==1 and cat[0]=='S':

print('There is a return delay, fine of Rs 400 to be paid.')

else:

pass

except:

print('An unexpected error occurred, please try again')

print()

#returned books

def bookreturn():

try:

issueid=int(input('Enter ID of the issuer returning the book: '))

B_id=int(input('Enter the ID of the returned book: '))

run='DELETE FROM issue_records WHERE I_id={}'.format(issueid)

cur.execute(run)

db.commit()

inc='UPDATE Books SET B_copies=B_copies+1 WHERE B_id={}'.format(B_id)

cur.execute(inc)

db.commit()

print('Book return registered')

print()

except:
print('An unexpected error occurred, please try again')

db.rollback()

print()

#Main Code

try:

pwd=input('Enter your SQL password: ')

db=ms.connect(host='localhost',user='root',passwd=pwd) #connector object

except:

print('Incorrect SQL password entered')

cur=db.cursor() #cursor object

print("Welcome to the Library Management System!") #introduction to the


management system

print()

print('''Below are a few features of this management system:

1. The records for all books in the library are saved in the "Books" table

2. The records for people issuing the books are saved in the "issue_records"
table

3. Issue records have to be deleted by the librarian when a book is


returned, using the function provided in the menu.

4. A book must be returned within 3 weeks of issuing else the issuer (if a
student) will have to pay a return delay fine of Rs 400.''')

print() #database creation and use

dbcheck=input("Do you already have the database 'library' created? y/n: ")

try:

if dbcheck.upper()=='Y':

cur.execute("USE library;")
print("'library' database in use.")

elif dbcheck.upper()=='N':

cur.execute ('CREATE DATABASE library')

cur.execute('USE library')

db.commit()

print('library database created and currently in use.')

#issuer table creation

itable='''CREATE TABLE issue_records( I_id int primary key,

name varchar(30) not null,

category char(1),

B_id int not null,

I_date date not null)'''

cur.execute(itable)

db.commit()

#book table creation

btable='''CREATE TABLE Books( B_id int primary key,

B_name varchar(50) not null,

B_author varchar(40),

B_genre varchar(40),

B_copies int not null);'''

cur.execute(btable)

db.commit()

else:

print('Please enter a valid input.')

except:

if dbcheck.upper()=='Y':
print("database 'library' does not exist.")

else:

print("database 'library' exists, using 'library'.")

#MAIN MENU

while True:

print()

print('''Choose the valid option to access related functions

1. Edit book table

2. View from book table

3. Edit issue table

4. View from issue table

5. Check for return delay by a particular issuer

6. Exit''')

print()

ch=int(input('Enter choice: '))

print()

if ch==1:

#altering book table menu

while True:

print('''Choose valid option to use functions

1. Add books

2. Change number of copies for a book

3. Delete records for a book

4. Return to main menu''')

print()

nch=int(input('Enter choice: '))


if nch==1:

addbk()

print()

elif nch==2:

change()

print()

elif nch==3:

delbook()

print()

elif nch==4:

print('Returning to main menu')

print()

break

else: print('Invalid input')

print()

elif ch==2: #viewing from book table menu

while True:

print('''Choose valid option to use functions

1. View records for all books

2. search for a specific record (via book ID or book name)

3. View all books by a particular author

4. View all books of a perticular genre

5. Return to main menu''')

print()

nch=int(input('Enter choice: '))

if nch==1:

viewallbooks()
print()

elif nch==2:

search()

print()

elif nch==3:

author()

print()

elif nch==4:

genre()

print()

elif nch==5:

print('Returning to main menu')

print()

break

else:

print('Invalid input')

elif ch==3:

#altering issue table menu

while True:

print('''Choose valid option to use functions

1. Add issue records

2. Delete issue records

3. Register a book return

4. Return to main menu''')

print()

nch=int(input('Enter choice: '))

if nch==1:
addrec()

print()

elif nch==2:

delissue()

print()

elif nch==3:

bookreturn()

print()

elif nch==4:

print('Returning to main menu')

print()

break

else:

print('Invalid input')

print()

elif ch==4:

#viewing from issue table menu

while True:

print('''Choose valid option to use functions

1. View all issue records

2. Search for a specific record (via issuer's ID or name)

3. View all issuers of a particular book

4. View records for all students/ all teachers

5. View all issuers for a particular date

6. Return to main menu''')

print()

nch=int(input('Enter choice: '))


if nch==1:

viewallissues()

print()

elif nch==2:

checkrecords()

print()

elif nch==3:

findwho()

print()

elif nch==4:

showselrec()

print()

elif nch==5:

dateissue()

print()

elif nch==6:

print('Returning to main menu')

print()

break

else:

print('Invalid input')

print()

elif ch==5:

checkdelay()

print()

elif ch==6:

print('Program terminated.')
break

else:

print('Please enter a valid input')

print()
OUTPUT

You might also like