Project Work Class
Project Work Class
Project Work Class
1. import psycopg2: This line imports the psycopg2 library, which is used to
interact with PostgreSQL databases from Python.
2. def create_tables():: This line defines a function named create_tables.
This function will be responsible for creating tables in a PostgreSQL
database related to a library system.
3. try:: The start of a try-except block in Python, where the code inside the
try block is executed, and any exceptions that occur are handled in the
except block.
4. conn =
psycopg2.connect(database='library_sys',user='postgres',password='’):
This line establishes a connection to a PostgreSQL database named
library_sys with the username postgres and appropriate password ''. It
assigns the connection object to the variable conn.
5. cursor = conn.cursor(): This line creates a cursor object using the
connection conn. Cursors are used to execute SQL commands in
PostgreSQL.
6. cursor.execute("""CREATE TABLE IF NOT EXISTS books (book_id SERIAL
PRIMARY KEY, title VARCHAR(255), author VARCHAR(255), isbn
VARCHAR(20), available BOOLEAN);"""): This SQL command executed
through cursor.execute() creates a table named books if it does not
already exist. The table has columns for book_id (auto-incrementing
SERIAL primary key), title, author, isbn, and available.
7. Similar CREATE TABLE commands follow for two more tables: borrowers
and transactions, defining their respective columns and relationships.
8. conn.commit(): Commits the transaction to the database, making all
changes made within the transaction permanent.
9. print("Tables created successfully!"): Prints a message indicating that the
tables were created successfully.
10. except psycopg2.Error as e:: This block catches any exceptions that occur
during the execution of the code within the try block and assigns the
exception object to the variable e.
11. print("Error creating tables:", e): If an error occurs in the try block, this
line prints an error message along with details of the exception.
12. finally:: This block of code ensures that certain actions are performed
regardless of whether an exception occurred or not.
13. if conn: conn.close(): If the connection conn exists (was successfully
opened), it is closed in the finally block to ensure proper cleanup.
14. create_tables(): Finally, this line calls the create_tables() function,
initiating the process of creating the tables in the PostgreSQL database.
This code essentially establishes a connection to a PostgreSQL database and
creates three tables (books, borrowers, and transactions) if they do not exist,
defining their respective columns. It then commits these changes to the
database and prints a success message or handles any errors that may occur
during this process.
PROGRAM CODE:
#pip install psycopg2 in cmd at first
import psycopg2
def create_tables():
try:
conn =
psycopg2.connect(database='library_sys',user='postgres',password='')
cursor = conn.cursor()
cursor.execute("""
title VARCHAR(255),
author VARCHAR(255),
isbn VARCHAR(20),
available BOOLEAN
);
""")
name VARCHAR(255),
email VARCHAR(100)
);
""")
cursor.execute("""
borrowed_date DATE,
return_date DATE,
returned BOOLEAN
);
""")
except psycopg2.Error as e:
finally:
if conn:
conn.close()
create_tables()
FUNCTIONS THAT ARE REQUIRED FOR THE LIBRARY
MANAGEMENT SYSTEM
1. Function connect_db()
Similar to add_book(), this function adds a new borrower to the borrowers table
within the library_sys database.
It inserts borrower details (name and email) into the borrowers table, commits
the changes to the database, handles errors, and closes the connection if it
exists, following similar exception handling practices as seen in add_book().
4. Function borrow_book()
This function manages the process of borrowing a book from the library system.
This function updates the availability status of a book to False in the books table
and inserts a new transaction record into the transactions table, indicating that
the book has been borrowed by a particular borrower. It uses the provided book
ID, borrower ID, return date, and manages exceptions as seen in previous
functions.
5. Function delete_transactions_for_book()
This function allows users to search for books in the library based on specific
criteria (such as title or author) and a provided keyword.
This function performs a search operation based on the given criteria (either title
or author) and the provided keyword. It constructs an appropriate SQL query
based on the criteria and retrieves books matching the criteria, displaying their
information.
7. Function display_books()
This function retrieves all books from the transactions table in the database and
displays their information.
It retrieves all book records from the transactions table and prints their details
using a loop. Similar to other functions, it handles any potential errors and
ensures proper closing of the connection.
8. Function main()
The main() function is the primary entry point of the program. It orchestrates
the interactions between the user and the database functions through a menu-
driven interface.
This function continuously prompts the user with a menu of options and
performs actions based on the user's input by invoking the respective functions
defined earlier. It continues until the user chooses to exit the program (choice
== '0').
9. if __name__ == "__main__":
This conditional block checks if the current script is the main program being
executed directly (not imported as a module). If so, it calls the main() function
to start the library management system.
This detailed breakdown illustrates how each function in the code contributes to
the library management system, handling database interactions for adding
books and borrowers, managing transactions, searching books, displaying book
information, and providing a user-friendly menu-driven interface to perform
these actions.
PROGRAM CODE:
def connect_db():
try:
conn=psycopg2.connect(database='library_sys',user='postgres',password='')
return conn
except psycopg2.Error as e:
return None
try:
conn =
psycopg2.connect(database='library_sys',user='postgres',password='')
cursor = conn.cursor()
conn.commit()
except psycopg2.Error as e:
finally:
if conn:
conn.close()
try:
conn =
psycopg2.connect(database='library_sys',user='postgres',password='')
cursor = conn.cursor()
conn.commit()
except psycopg2.Error as e:
finally:
if conn:
conn.close()
#borrow book
try:
conn =
psycopg2.connect(database='library_sys',user='postgres',password='')
cursor = conn.cursor()
conn.commit()
except psycopg2.Error as e:
finally:
if conn:
conn.close()
def delete_transactions_for_book(book_id):
try:
conn =
psycopg2.connect(database='library_sys',user='postgres',password='')
cursor = conn.cursor()
conn.commit()
except psycopg2.Error as e:
finally:
if conn:
conn.close()
try:
conn =
psycopg2.connect(database='library_sys',user='postgres',password='')
cursor = conn.cursor()
if criteria.lower() == 'title':
else:
return
books = cursor.fetchall()
except psycopg2.Error as e:
finally:
if conn:
conn.close()
def display_books():
try:
conn=
psycopg2.connect(database='library_sys',user='postgres',password='')
cursor = conn.cursor()
book_status=cursor.fetchall()
print(status)
books = cursor.fetchall()
print(book)
borrow_status=cursor.fetchall()
print(borrow)
except psycopg2.Error as e:
if conn:
conn.close()
def main():
connect_db()
while True:
print("Choose an action:")
print("3. Delete")
print("4. Search")
print("5. Display")
print("0. Exit")
if choice == '1':
for i in range(n):
# Usage of borrower
add_borrower(borrower_name, email_id)
borrow_book(book_id,borrower_id,return_date)
#add_borrower("Subhojit", "subhojit@gmail.com")
#borrow_book(1, 1, '2023-12-31')
#borrow_book(3, 2, '2023-12-17')
delete_transactions_for_book(dlt)
delete_transactions_for_book(dlt)
# Usage
# Usage
display_books()
break
else:
if __name__ == "__main__":
main()
OUTPUT:
1. Adding a book:
2. Borrowing a book:
6. Delete transaction:
After deletion: (TRANSACTION STATUS)