Advanced Library Management System with Source Code

Python Project: Advanced Library Management System with Source Code

Hello, dosto! Welcome to this massive, super exciting blog post where we’re going to build an Advanced Library Management System using Python. This isn’t just some basic project—it’s a full-on, feature-packed system that can handle everything a library needs, from managing books to tracking members, issuing books, calculating fines, and generating reports. 

Advanced Library Management System

Why a Library Management System?

Arre, before we start typing code, let’s talk about why this project is such a cool idea. Libraries are like treasure houses, aren’t they? Rows of books, students borrowing novels, professors hunting for research journals—it’s a busy place! But managing all that manually? Uff, that’s a proper headache. Keeping track of which book is with whom, who’s late returning, and how much fine to charge—bhai, it’s a lot of work. That’s where our Advanced Library Management System comes in. It’s like giving the librarian a superhero cape! This system will automate everything: adding books, registering members, issuing and returning books, calculating fines, and even generating fancy reports. Plus, it’s a fantastic way to level up your Python skills and build something you can show off in your college project or portfolio.

This project is perfect for:

  • Students: Need a solid final-year project or something to impress your teacher? This is it.
  • Beginners: New to Python? This project will teach you variables, functions, databases, and more in a fun way.
  • Developers: Want to create a real-world app? You can extend this to a web or mobile app later.

We’re using Python because it’s simple, powerful, and has libraries (pun intended!) that make coding a breeze. We’ll also use SQLite for storing data and keep the interface console-based to keep things beginner-friendly. By the end, you’ll have a complete system with source code you can run yourself. Ready? Chalo, let’s get started!

Project Overview

Our Advanced Library Management System will have all the features a modern library needs. Here’s what we’re building:

  1. Book Management: Add new books, update their details, delete them, or search by title, author, or ISBN.
  2. Member Management: Register new members, update their info, delete them, or view their details.
  3. Borrowing System: Issue books to members and keep track of who borrowed what.
  4. Return System: Handle book returns and calculate fines for late returns.
  5. Fine Calculation: Automatically calculate fines (say, Rs. 10 per day) for overdue books.
  6. Search Functionality: Search for books using keywords—super handy for finding that one novel you want!
  7. Reports: Generate reports like a list of borrowed books, overdue books, or member details.
  8. Console Interface: A simple text-based menu to interact with the system (we’ll talk about GUI upgrades later).
  9. Database Integration: Use SQLite to store all data securely and efficiently.

We’ll code this in Python 3.x, use SQLite for the database, and keep it simple with a console interface. The source code will be included, so you can copy-paste and run it. We’ll break it down step-by-step, explaining everything like I’m your coding bhai, sitting right next to you.

Tools and Technologies

Before we start, let’s gather our tools—like packing your bag before a trip to the library! Here’s what you need:

  • Python 3.x: Make sure you have Python installed. Download it from python.org if you don’t.
  • SQLite: This is a lightweight database that comes built-in with Python—no extra installation needed.
  • Text Editor/IDE: Use VS Code, PyCharm, or even Notepad++ (whatever you’re comfortable with, yaar).
  • Basic Python Knowledge: You should know variables, loops, functions, and maybe a bit about classes. Don’t worry, we’ll explain everything!
  • Python Libraries: We’ll use sqlite3 for the database and datetime for handling dates. No external libraries, so it’s super easy to set up.

If you don’t have Python installed, go to python.org, download the latest version, and install it. SQLite is already part of Python, so no tension there. Alright, let’s set up the project structure!

Project Setup

First, create a folder for our project. Call it LibraryManagementSystem or something desi like PustakalayApp. Inside this folder, create a Python file called library.py. This will be our main file where all the action happens. Here’s how your folder should look:

LibraryManagementSystem/
├── library.py
├── library.db (this will be created automatically by SQLite)

No need for extra files yet—we’ll keep it simple. Open library.py in your text editor, and let’s start coding. We’ll build this system step-by-step, starting with the database, then adding features one by one. Each section will have explanations, code, and examples, so you won’t feel lost, bhai.

Setting Up the Database

Since we’re using SQLite, we need a database to store all our data. We’ll create three tables:

  • Books: To store book details like title, author, ISBN, publication year, and status (Available or Issued).
  • Members: To store member details like name, email, phone, and join date.
  • Transactions: To track borrowing and returning, including issue dates, due dates, and fines.

Let’s write the code to create these tables. Open library.py and add this:

import sqlite3
from datetime import datetime, timedelta
import uuid

# Connect to SQLite database (creates a new database if it doesn't exist)
def init_db():
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()

    # Create Books table
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS books (
            book_id TEXT PRIMARY KEY,
            title TEXT NOT NULL,
            author TEXT NOT NULL,
            isbn TEXT UNIQUE NOT NULL,
            publication_year INTEGER,
            status TEXT DEFAULT 'Available'
        )
    ''')

    # Create Members table
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS members (
            member_id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            email TEXT UNIQUE NOT NULL,
            phone TEXT,
            join_date TEXT
        )
    ''')

    # Create Transactions table
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS transactions (
            transaction_id TEXT PRIMARY KEY,
            book_id TEXT,
            member_id TEXT,
            issue_date TEXT,
            due_date TEXT,
            return_date TEXT,
            fine_amount REAL DEFAULT 0.0,
            FOREIGN KEY (book_id) REFERENCES books (book_id),
            FOREIGN KEY (member_id) REFERENCES members (member_id)
        )
    ''')

    conn.commit()
    conn.close()
    print("Database initialized successfully! Aur kya chahiye?")

# Initialize the database when the script runs
if __name__ == "__main__":
    init_db()

Explanation

  • We import sqlite3 for database operations, datetime and timedelta for handling dates, and uuid for generating unique IDs.
  • The init_db() function connects to library.db (it’ll create the file automatically if it doesn’t exist).
  • We create three tables:
    • Books: Stores book details with a unique book_id (using UUID), title, author, ISBN, publication year, and status.
    • Members: Stores member details like member_id, name, email, phone, and join date.
    • Transactions: Tracks borrowing with transaction_id, book_id, member_id, issue date, due date, return date, and fine amount.
  • The FOREIGN KEY constraints ensure transactions link to valid books and members.
  • When you run this code, it creates library.db in your project folder and prints a success message.

Run this code, and you’ll see library.db in your folder. You can open it with an SQLite viewer (like DB Browser for SQLite) to check the tables. Now, let’s add functions to manage books!

Managing Books

Time to add some meat to our system! We need functions to add, update, delete, and search books. These are the core operations for managing the library’s collection. Add this code to library.py:

# Add a new book
def add_book(title, author, isbn, publication_year):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    book_id = str(uuid.uuid4())
    
    try:
        cursor.execute('''
            INSERT INTO books (book_id, title, author, isbn, publication_year, status)
            VALUES (?, ?, ?, ?, ?, ?)
        ''', (book_id, title, author, isbn, publication_year, 'Available'))
        conn.commit()
        print(f"Book '{title}' added successfully with ID: {book_id}. Bas, ho gaya!")
    except sqlite3.IntegrityError:
        print("Arre, error! A book with this ISBN already exists!")
    finally:
        conn.close()

# Update book details
def update_book(book_id, title=None, author=None, isbn=None, publication_year=None):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    updates = {}
    if title:
        updates['title'] = title
    if author:
        updates['author'] = author
    if isbn:
        updates['isbn'] = isbn
    if publication_year:
        updates['publication_year'] = publication_year
    
    if updates:
        query = "UPDATE books SET " + ", ".join(f"{key} = ?" for key in updates.keys()) + " WHERE book_id = ?"
        values = list(updates.values()) + [book_id]
        cursor.execute(query, values)
        conn.commit()
        print(f"Book with ID {book_id} updated successfully! Chalo, good job!")
    else:
        print("Kuch nahi diya to update kya karu?")
    conn.close()

# Delete a book
def delete_book(book_id):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    cursor.execute("SELECT status FROM books WHERE book_id = ?", (book_id,))
    book = cursor.fetchone()
    
    if book:
        if book[0] == 'Available':
            cursor.execute("DELETE FROM books WHERE book_id = ?", (book_id,))
            conn.commit()
            print(f"Book with ID {book_id} deleted successfully! Done and dusted!")
        else:
            print("Arre, error! Cannot delete book because it’s currently issued!")
    else:
        print("Oops, book not found, bhai!")
    conn.close()

# Search for books
def search_books(search_term):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    cursor.execute('''
        SELECT * FROM books 
        WHERE title LIKE ? OR author LIKE ? OR isbn LIKE ?
    ''', (f'%{search_term}%', f'%{search_term}%', f'%{search_term}%'))
    
    books = cursor.fetchall()
    if books:
        print("\nSearch Results:")
        for book in books:
            print(f"ID: {book[0]}, Title: {book[1]}, Author: {book[2]}, ISBN: {book[3]}, Year: {book[4]}, Status: {book[5]}")
    else:
        print("Koi book nahi mili, bhai!")
    conn.close()

# Test the book management functions
if __name__ == "__main__":
    init_db()
    add_book("The Great Gatsby", "F. Scott Fitzgerald", "978-0743273565", 1925)
    add_book("To Kill a Mockingbird", "Harper Lee", "978-0446310789", 1960)
    search_books("Gatsby")
    update_book("some-book-id", title="The Great Gatsby (Updated)")
    delete_book("some-book-id")

Explanation

  • Add Book: Generates a unique book_id using UUID, inserts the book into the books table, and sets its status to "Available". It checks for duplicate ISBNs to avoid errors.
  • Update Book: Updates specific fields (title, author, etc.) for a book using its book_id. It builds the SQL query dynamically based on what’s provided.
  • Delete Book: Checks if the book exists and is available (not issued) before deleting it.
  • Search Books: Searches for books by title, author, or ISBN using a LIKE query with wildcards (% for partial matches).
  • The test code adds two books, searches for "Gatsby", updates a book’s title, and tries to delete one (replace "some-book-id" with an actual ID when testing).

Run this code, and you’ll see books being added to the database. Use an SQLite viewer to check the books table—it’ll have your data!

Managing Members

Next, let’s handle library members. We need to register new members, update their details, delete them, and view their info. Add this to library.py:

# Add a new member
def add_member(name, email, phone):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    member_id = str(uuid.uuid4())
    join_date = datetime.now().strftime("%Y-%m-%d")
    
    try:
        cursor.execute('''
            INSERT INTO members (member_id, name, email, phone, join_date)
            VALUES (?, ?, ?, ?, ?)
        ''', (member_id, name, email, phone, join_date))
        conn.commit()
        print(f"Member '{name}' added successfully with ID: {member_id}. Welcome to the library!")
    except sqlite3.IntegrityError:
        print("Arre, error! A member with this email already exists!")
    finally:
        conn.close()

# Update member details
def update_member(member_id, name=None, email=None, phone=None):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    updates = {}
    if name:
        updates['name'] = name
    if email:
        updates['email'] = email
    if phone:
        updates['phone'] = phone
    
    if updates:
        query = "UPDATE members SET " + ", ".join(f"{key} = ?" for key in updates.keys()) + " WHERE member_id = ?"
        values = list(updates.values()) + [member_id]
        cursor.execute(query, values)
        conn.commit()
        print(f"Member with ID {member_id} updated successfully! Sab set hai!")
    else:
        print("Kuch nahi diya to update kya karu?")
    conn.close()

# Delete a member
def delete_member(member_id):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    cursor.execute("SELECT * FROM transactions WHERE member_id = ? AND return_date IS NULL", (member_id,))
    active_transactions = cursor.fetchone()
    
    if active_transactions:
        print("Arre, error! Cannot delete member because they have books issued!")
    else:
        cursor.execute("DELETE FROM members WHERE member_id = ?", (member_id,))
        conn.commit()
        print(f"Member with ID {member_id} deleted successfully! Bye-bye!")
    conn.close()

# View member details
def view_member(member_id):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    cursor.execute("SELECT * FROM members WHERE member_id = ?", (member_id,))
    member = cursor.fetchone()
    
    if member:
        print(f"\nMember Details:\nID: {member[0]}\nName: {member[1]}\nEmail: {member[2]}\nPhone: {member[3]}\nJoin Date: {member[4]}")
    else:
        print("Oops, member not found, bhai!")
    conn.close()

# Test the member management functions
if __name__ == "__main__":
    init_db()
    add_book("The Great Gatsby", "F. Scott Fitzgerald", "978-0743273565", 1925)
    add_member("Rahul Sharma", "rahul@example.com", "9876543210")
    view_member("some-member-id")
    update_member("some-member-id", name="Rahul Kumar")
    delete_member("some-member-id")

Explanation

  • Add Member: Generates a unique member_id, records the join date, and adds the member to the members table. It checks for duplicate emails.
  • Update Member: Updates specific fields (name, email, phone) for a member using their member_id.
  • Delete Member: Checks if the member has active borrowed books (unreturned transactions) before deleting.
  • View Member: Displays a member’s details by their member_id.
  • The test code adds a member, views their details, updates their name, and tries to delete them (replace "some-member-id" with an actual ID).

Borrowing and Returning Books

Now, let’s get to the fun part—issuing and returning books! When a member borrows a book, we’ll mark it as "Issued" and create a transaction. When they return it, we’ll calculate fines (if any) and mark the book as "Available". Add this to library.py:

# Issue a book to a member
def issue_book(book_id, member_id):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    # Check if book exists and is available
    cursor.execute("SELECT status FROM books WHERE book_id = ?", (book_id,))
    book = cursor.fetchone()
    
    # Check if member exists
    cursor.execute("SELECT * FROM members WHERE member_id = ?", (member_id,))
    member = cursor.fetchone()
    
    if not book:
        print("Arre, book nahi mili!")
        conn.close()
        return
    if not member:
        print("Member nahi hai, bhai!")
        conn.close()
        return
    if book[0] != 'Available':
        print("Sorry, book already issued hai!")
        conn.close()
        return
    
    transaction_id = str(uuid.uuid4())
    issue_date = datetime.now().strftime("%Y-%m-%d")
    due_date = (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d")
    
    cursor.execute('''
        INSERT INTO transactions (transaction_id, book_id, member_id, issue_date, due_date)
        VALUES (?, ?, ?, ?, ?)
    ''', (transaction_id, book_id, member_id, issue_date, due_date))
    
    cursor.execute("UPDATE books SET status = 'Issued' WHERE book_id = ?", (book_id,))
    conn.commit()
    print(f"Book issued successfully! Transaction ID: {transaction_id}, Due Date: {due_date}. Enjoy reading!")
    conn.close()

# Return a book
def return_book(transaction_id):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    cursor.execute("SELECT book_id, due_date FROM transactions WHERE transaction_id = ? AND return_date IS NULL", (transaction_id,))
    transaction = cursor.fetchone()
    
    if not transaction:
        print("Arre, transaction nahi mili or book already returned hai!")
        conn.close()
        return
    
    book_id, due_date = transaction
    return_date = datetime.now().strftime("%Y-%m-%d")
    due_date = datetime.strptime(due_date, "%Y-%m-%d")
    return_date_dt = datetime.strptime(return_date, "%Y-%m-%d")
    
    # Calculate fine (Rs. 10 per day after due date)
    fine = 0.0
    if return_date_dt > due_date:
        days_late = (return_date_dt - due_date).days
        fine = days_late * 10.0
    
    cursor.execute('''
        UPDATE transactions 
        SET return_date = ?, fine_amount = ? 
        WHERE transaction_id = ?
    ''', (return_date, fine, transaction_id))
    
    cursor.execute("UPDATE books SET status = 'Available' WHERE book_id = ?", (book_id,))
    conn.commit()
    
    if fine > 0:
        print(f"Book returned successfully! Fine: Rs. {fine}. Jaldi return karo next time!")
    else:
        print("Book returned successfully! No fine, good job!")
    conn.close()

# Test borrowing and returning
if __name__ == "__main__":
    init_db()
    add_book("The Great Gatsby", "F. Scott Fitzgerald", "978-0743273565", 1925)
    add_member("Rahul Sharma", "rahul@example.com", "9876543210")
    issue_book("some-book-id", "some-member-id")
    return_book("some-transaction-id")

Explanation

  • Issue Book: Checks if the book is available and the member exists, creates a transaction with a 14-day due date, and marks the book as "Issued".
  • Return Book: Finds the transaction, calculates fines (Rs. 10 per day late), updates the return date and fine, and sets the book status to "Available".
  • The fine calculation is simple: if the return date is past the due date, we charge Rs. 10 per day.

Generating Reports

Let’s add some report-generating functions to make the system more useful for library admins. We’ll create reports for borrowed books and overdue books. Add this to library.py:

# View all borrowed books
def view_borrowed_books():
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    cursor.execute('''
        SELECT t.transaction_id, b.title, m.name, t.issue_date, t.due_date
        FROM transactions t
        JOIN books b ON t.book_id = b.book_id
        JOIN members m ON t.member_id = m.member_id
        WHERE t.return_date IS NULL
    ''')
    
    transactions = cursor.fetchall()
    if transactions:
        print("\nBorrowed Books:")
        for t in transactions:
            print(f"Transaction ID: {t[0]}, Book: {t[1]}, Member: {t[2]}, Issued: {t[3]}, Due: {t[4]}")
    else:
        print("Koi book borrowed nahi hai abhi!")
    conn.close()

# View overdue books
def view_overdue_books():
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    current_date = datetime.now().strftime("%Y-%m-%d")
    cursor.execute('''
        SELECT t.transaction_id, b.title, m.name, t.due_date
        FROM transactions t
        JOIN books b ON t.book_id = b.book_id
        JOIN members m ON t.member_id = m.member_id
        WHERE t.return_date IS NULL AND t.due_date < ?
    ''', (current_date,))
    
    transactions = cursor.fetchall()
    if transactions:
        print("\nOverdue Books:")
        for t in transactions:
            print(f"Transaction ID: {t[0]}, Book: {t[1]}, Member: {t[2]}, Due: {t[3]}")
    else:
        print("Koi overdue books nahi hai, sab time pe return kar rahe hai!")
    conn.close()

# Test reports
if __name__ == "__main__":
    init_db()
    view_borrowed_books()
    view_overdue_books()

Explanation

  • View Borrowed Books: Joins the transactions, books, and members tables to show all currently borrowed books with details like transaction ID, book title, member name, issue date, and due date.
  • View Overdue Books: Shows books that are past their due date and haven’t been returned yet.

Creating a User Interface

To make the system user-friendly, let’s add a console-based menu so users can choose what to do. This will tie everything together. Add this to library.py:

def main_menu():
    while True:
        print("\n=== Library Management System ===")
        print("1. Add Book")
        print("2. Update Book")
        print("3. Delete Book")
        print("4. Search Books")
        print("5. Add Member")
        print("6. Update Member")
        print("7. Delete Member")
        print("8. View Member")
        print("9. Issue Book")
        print("10. Return Book")
        print("11. View Borrowed Books")
        print("12. View Overdue Books")
        print("13. Exit")
        
        choice = input("Enter your choice (1-13): ")
        
        if choice == '1':
            title = input("Enter book title: ")
            author = input("Enter author name: ")
            isbn = input("Enter ISBN: ")
            year = input("Enter publication year: ")
            add_book(title, author, isbn, int(year))
        
        elif choice == '2':
            book_id = input("Enter book ID: ")
            title = input("Enter new title (or press Enter to skip): ")
            author = input("Enter new author (or press Enter to skip): ")
            isbn = input("Enter new ISBN (or press Enter to skip): ")
            year = input("Enter new publication year (or press Enter to skip): ")
            update_book(book_id, title or None, author or None, isbn or None, int(year) if year else None)
        
        elif choice == '3':
            book_id = input("Enter book ID to delete: ")
            delete_book(book_id)
        
        elif choice == '4':
            search_term = input("Enter search term (title, author, or ISBN): ")
            search_books(search_term)
        
        elif choice == '5':
            name = input("Enter member name: ")
            email = input("Enter email: ")
            phone = input("Enter phone number: ")
            add_member(name, email, phone)
        
        elif choice == '6':
            member_id = input("Enter member ID: ")
            name = input("Enter new name (or press Enter to skip): ")
            email = input("Enter new email (or press Enter to skip): ")
            phone = input("Enter new phone (or press Enter to skip): ")
            update_member(member_id, name or None, email or None, phone or None)
        
        elif choice == '7':
            member_id = input("Enter member ID to delete: ")
            delete_member(member_id)
        
        elif choice == '8':
            member_id = input("Enter member ID to view: ")
            view_member(member_id)
        
        elif choice == '9':
            book_id = input("Enter book ID: ")
            member_id = input("Enter member ID: ")
            issue_book(book_id, member_id)
        
        elif choice == '10':
            transaction_id = input("Enter transaction ID: ")
            return_book(transaction_id)
        
        elif choice == '11':
            view_borrowed_books()
        
        elif choice == '12':
            view_overdue_books()
        
        elif choice == '13':
            print("Thank you for using the Library Management System. Chalte hai ab!")
            break
        
        else:
            print("Galat choice, bhai! Try again.")

if __name__ == "__main__":
    init_db()
    main_menu()

Explanation

  • The main_menu() function shows a menu with 13 options and uses input() to get the user’s choice.
  • Based on the choice, it calls the appropriate function and collects necessary inputs (e.g., book title, member ID).
  • The loop runs until the user selects "Exit" (option 13).
  • The messages are kept fun and desi to make the experience lively!

Complete Source Code

Here’s the complete library.py file with all the code combined. Copy-paste this into your library.py file to run the system:

import sqlite3
from datetime import datetime, timedelta
import uuid

# Connect to SQLite database (creates a new database if it doesn't exist)
def init_db():
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()

    # Create Books table
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS books (
            book_id TEXT PRIMARY KEY,
            title TEXT NOT NULL,
            author TEXT NOT NULL,
            isbn TEXT UNIQUE NOT NULL,
            publication_year INTEGER,
            status TEXT DEFAULT 'Available'
        )
    ''')

    # Create Members table
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS members (
            member_id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            email TEXT UNIQUE NOT NULL,
            phone TEXT,
            join_date TEXT
        )
    ''')

    # Create Transactions table
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS transactions (
            transaction_id TEXT PRIMARY KEY,
            book_id TEXT,
            member_id TEXT,
            issue_date TEXT,
            due_date TEXT,
            return_date TEXT,
            fine_amount REAL DEFAULT 0.0,
            FOREIGN KEY (book_id) REFERENCES books (book_id),
            FOREIGN KEY (member_id) REFERENCES members (member_id)
        )
    ''')

    conn.commit()
    conn.close()
    print("Database initialized successfully! Aur kya chahiye?")

# Add a new book
def add_book(title, author, isbn, publication_year):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    book_id = str(uuid.uuid4())
    
    try:
        cursor.execute('''
            INSERT INTO books (book_id, title, author, isbn, publication_year, status)
            VALUES (?, ?, ?, ?, ?, ?)
        ''', (book_id, title, author, isbn, publication_year, 'Available'))
        conn.commit()
        print(f"Book '{title}' added successfully with ID: {book_id}. Bas, ho gaya!")
    except sqlite3.IntegrityError:
        print("Arre, error! A book with this ISBN already exists!")
    finally:
        conn.close()

# Update book details
def update_book(book_id, title=None, author=None, isbn=None, publication_year=None):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    updates = {}
    if title:
        updates['title'] = title
    if author:
        updates['author'] = author
    if isbn:
        updates['isbn'] = isbn
    if publication_year:
        updates['publication_year'] = publication_year
    
    if updates:
        query = "UPDATE books SET " + ", ".join(f"{key} = ?" for key in updates.keys()) + " WHERE book_id = ?"
        values = list(updates.values()) + [book_id]
        cursor.execute(query, values)
        conn.commit()
        print(f"Book with ID {book_id} updated successfully! Chalo, good job!")
    else:
        print("Kuch nahi diya to update kya karu?")
    conn.close()

# Delete a book
def delete_book(book_id):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    cursor.execute("SELECT status FROM books WHERE book_id = ?", (book_id,))
    book = cursor.fetchone()
    
    if book:
        if book[0] == 'Available':
            cursor.execute("DELETE FROM books WHERE book_id = ?", (book_id,))
            conn.commit()
            print(f"Book with ID {book_id} deleted successfully! Done and dusted!")
        else:
            print("Arre, error! Cannot delete book because it’s currently issued!")
    else:
        print("Oops, book not found, bhai!")
    conn.close()

# Search for books
def search_books(search_term):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    cursor.execute('''
        SELECT * FROM books 
        WHERE title LIKE ? OR author LIKE ? OR isbn LIKE ?
    ''', (f'%{search_term}%', f'%{search_term}%', f'%{search_term}%'))
    
    books = cursor.fetchall()
    if books:
        print("\nSearch Results:")
        for book in books:
            print(f"ID: {book[0]}, Title: {book[1]}, Author: {book[2]}, ISBN: {book[3]}, Year: {book[4]}, Status: {book[5]}")
    else:
        print("Koi book nahi mili, bhai!")
    conn.close()

# Add a new member
def add_member(name, email, phone):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    member_id = str(uuid.uuid4())
    join_date = datetime.now().strftime("%Y-%m-%d")
    
    try:
        cursor.execute('''
            INSERT INTO members (member_id, name, email, phone, join_date)
            VALUES (?, ?, ?, ?, ?)
        ''', (member_id, name, email, phone, join_date))
        conn.commit()
        print(f"Member '{name}' added successfully with ID: {member_id}. Welcome to the library!")
    except sqlite3.IntegrityError:
        print("Arre, error! A member with this email already exists!")
    finally:
        conn.close()

# Update member details
def update_member(member_id, name=None, email=None, phone=None):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    updates = {}
    if name:
        updates['name'] = name
    if email:
        updates['email'] = email
    if phone:
        updates['phone'] = phone
    
    if updates:
        query = "UPDATE members SET " + ", ".join(f"{key} = ?" for key in updates.keys()) + " WHERE member_id = ?"
        values = list(updates.values()) + [member_id]
        cursor.execute(query, values)
        conn.commit()
        print(f"Member with ID {member_id} updated successfully! Sab set hai!")
    else:
        print("Kuch nahi diya to update kya karu?")
    conn.close()

# Delete a member
def delete_member(member_id):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    cursor.execute("SELECT * FROM transactions WHERE member_id = ? AND return_date IS NULL", (member_id,))
    active_transactions = cursor.fetchone()
    
    if active_transactions:
        print("Arre, error! Cannot delete member because they have books issued!")
    else:
        cursor.execute("DELETE FROM members WHERE member_id = ?", (member_id,))
        conn.commit()
        print(f"Member with ID {member_id} deleted successfully! Bye-bye!")
    conn.close()

# View member details
def view_member(member_id):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    cursor.execute("SELECT * FROM members WHERE member_id = ?", (member_id,))
    member = cursor.fetchone()
    
    if member:
        print(f"\nMember Details:\nID: {member[0]}\nName: {member[1]}\nEmail: {member[2]}\nPhone: {member[3]}\nJoin Date: {member[4]}")
    else:
        print("Oops, member not found, bhai!")
    conn.close()

# Issue a book to a member
def issue_book(book_id, member_id):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    # Check if book exists and is available
    cursor.execute("SELECT status FROM books WHERE book_id = ?", (book_id,))
    book = cursor.fetchone()
    
    # Check if member exists
    cursor.execute("SELECT * FROM members WHERE member_id = ?", (member_id,))
    member = cursor.fetchone()
    
    if not book:
        print("Arre, book nahi mili!")
        conn.close()
        return
    if not member:
        print("Member nahi hai, bhai!")
        conn.close()
        return
    if book[0] != 'Available':
        print("Sorry, book already issued hai!")
        conn.close()
        return
    
    transaction_id = str(uuid.uuid4())
    issue_date = datetime.now().strftime("%Y-%m-%d")
    due_date = (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d")
    
    cursor.execute('''
        INSERT INTO transactions (transaction_id, book_id, member_id, issue_date, due_date)
        VALUES (?, ?, ?, ?, ?)
    ''', (transaction_id, book_id, member_id, issue_date, due_date))
    
    cursor.execute("UPDATE books SET status = 'Issued' WHERE book_id = ?", (book_id,))
    conn.commit()
    print(f"Book issued successfully! Transaction ID: {transaction_id}, Due Date: {due_date}. Enjoy reading!")
    conn.close()

# Return a book
def return_book(transaction_id):
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    cursor.execute("SELECT book_id, due_date FROM transactions WHERE transaction_id = ? AND return_date IS NULL", (transaction_id,))
    transaction = cursor.fetchone()
    
    if not transaction:
        print("Arre, transaction nahi mili or book already returned hai!")
        conn.close()
        return
    
    book_id, due_date = transaction
    return_date = datetime.now().strftime("%Y-%m-%d")
    due_date = datetime.strptime(due_date, "%Y-%m-%d")
    return_date_dt = datetime.strptime(return_date, "%Y-%m-%d")
    
    # Calculate fine (Rs. 10 per day after due date)
    fine = 0.0
    if return_date_dt > due_date:
        days_late = (return_date_dt - due_date).days
        fine = days_late * 10.0
    
    cursor.execute('''
        UPDATE transactions 
        SET return_date = ?, fine_amount = ? 
        WHERE transaction_id = ?
    ''', (return_date, fine, transaction_id))
    
    cursor.execute("UPDATE books SET status = 'Available' WHERE book_id = ?", (book_id,))
    conn.commit()
    
    if fine > 0:
        print(f"Book returned successfully! Fine: Rs. {fine}. Jaldi return karo next time!")
    else:
        print("Book returned successfully! No fine, good job!")
    conn.close()

# View all borrowed books
def view_borrowed_books():
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    cursor.execute('''
        SELECT t.transaction_id, b.title, m.name, t.issue_date, t.due_date
        FROM transactions t
        JOIN books b ON t.book_id = b.book_id
        JOIN members m ON t.member_id = m.member_id
        WHERE t.return_date IS NULL
    ''')
    
    transactions = cursor.fetchall()
    if transactions:
        print("\nBorrowed Books:")
        for t in transactions:
            print(f"Transaction ID: {t[0]}, Book: {t[1]}, Member: {t[2]}, Issued: {t[3]}, Due: {t[4]}")
    else:
        print("Koi book borrowed nahi hai abhi!")
    conn.close()

# View overdue books
def view_overdue_books():
    conn = sqlite3.connect('library.db')
    cursor = conn.cursor()
    
    current_date = datetime.now().strftime("%Y-%m-%d")
    cursor.execute('''
        SELECT t.transaction_id, b.title, m.name, t.due_date
        FROM transactions t
        JOIN books b ON t.book_id = b.book_id
        JOIN members m ON t.member_id = m.member_id
        WHERE t.return_date IS NULL AND t.due_date < ?
    ''', (current_date,))
    
    transactions = cursor.fetchall()
    if transactions:
        print("\nOverdue Books:")
        for t in transactions:
            print(f"Transaction ID: {t[0]}, Book: {t[1]}, Member: {t[2]}, Due: {t[3]}")
    else:
        print("Koi overdue books nahi hai, sab time pe return kar rahe hai!")
    conn.close()

def main_menu():
    while True:
        print("\n=== Library Management System ===")
        print("1. Add Book")
        print("2. Update Book")
        print("3. Delete Book")
        print("4. Search Books")
        print("5. Add Member")
        print("6. Update Member")
        print("7. Delete Member")
        print("8. View Member")
        print("9. Issue Book")
        print("10. Return Book")
        print("11. View Borrowed Books")
        print("12. View Overdue Books")
        print("13. Exit")
        
        choice = input("Enter your choice (1-13): ")
        
        if choice == '1':
            title = input("Enter book title: ")
            author = input("Enter author name: ")
            isbn = input("Enter ISBN: ")
            year = input("Enter publication year: ")
            add_book(title, author, isbn, int(year))
        
        elif choice == '2':
            book_id = input("Enter book ID: ")
            title = input("Enter new title (or press Enter to skip): ")
            author = input("Enter new author (or press Enter to skip): ")
            isbn = input("Enter new ISBN (or press Enter to skip): ")
            year = input("Enter new publication year (or press Enter to skip): ")
            update_book(book_id, title or None, author or None, isbn or None, int(year) if year else None)
        
        elif choice == '3':
            book_id = input("Enter book ID to delete: ")
            delete_book(book_id)
        
        elif choice == '4':
            search_term = input("Enter search term (title, author, or ISBN): ")
            search_books(search_term)
        
        elif choice == '5':
            name = input("Enter member name: ")
            email = input("Enter email: ")
            phone = input("Enter phone number: ")
            add_member(name, email, phone)
        
        elif choice == '6':
            member_id = input("Enter member ID: ")
            name = input("Enter new name (or press Enter to skip): ")
            email = input("Enter new email (or press Enter to skip): ")
            phone = input("Enter new phone (or press Enter to skip): ")
            update_member(member_id, name or None, email or None, phone or None)
        
        elif choice == '7':
            member_id = input("Enter member ID to delete: ")
            delete_member(member_id)
        
        elif choice == '8':
            member_id = input("Enter member ID to view: ")
            view_member(member_id)
        
        elif choice == '9':
            book_id = input("Enter book ID: ")
            member_id = input("Enter member ID: ")
            issue_book(book_id, member_id)
        
        elif choice == '10':
            transaction_id = input("Enter transaction ID: ")
            return_book(transaction_id)
        
        elif choice == '11':
            view_borrowed_books()
        
        elif choice == '12':
            view_overdue_books()
        
        elif choice == '13':
            print("Thank you for using the Library Management System. Chalte hai ab!")
            break
        
        else:
            print("Galat choice, bhai! Try again.")

if __name__ == "__main__":
    init_db()
    main_menu()

Testing the System

To test the system, save the above code in library.py and run it using Python (python library.py). You’ll see the menu:

=== Library Management System ===
1. Add Book
2. Update Book
3. Delete Book
4. Search Books
5. Add Member
6. Update Member
7. Delete Member
8. View Member
9. Issue Book
10. Return Book
11. View Borrowed Books
12. View Overdue Books
13. Exit
Enter your choice (1-13): 

Try these steps:

  1. Add a Book: Choose option 1, enter details like "The Great Gatsby", "F. Scott Fitzgerald", "978-0743273565", and "1925". Note the book_id printed.
  2. Add a Member: Choose option 5, enter a name like "Rahul Sharma", email like "rahul@example.com", and phone like "9876543210". Note the member_id.
  3. Issue a Book: Choose option 9, enter the book_id and member_id. You’ll get a transaction_id and due date.
  4. Return a Book: Choose option 10, enter the transaction_id. Check if a fine is calculated (if returned late).
  5. Search Books: Choose option 4, search for "Gatsby" to see book details.
  6. View Reports: Choose options 11 and 12 to see borrowed and overdue books.

For example:

Enter your choice (1-13): 1
Enter book title: The Great Gatsby
Enter author name: F. Scott Fitzgerald
Enter ISBN: 978-0743273565
Enter publication year: 1925
Book 'The Great Gatsby' added successfully with ID: 123e4567-e89b-12d3-a456-426614174000. Bas, ho gaya!

Extending the System

Want to make this project even cooler? Here are some ideas to level it up:

  • GUI Interface: Use tkinter or PyQt to create a graphical interface with buttons and forms.
  • Web App: Convert this to a web app using Flask or Django. Store data in a database like PostgreSQL for scalability.
  • Email Notifications: Send email reminders for due dates using smtplib.
  • Barcode Scanner: Integrate a barcode scanner for ISBNs using Python libraries like pyzbar.
  • Fine Payment System: Add a feature to track fine payments and generate receipts.
  • Categories and Genres: Add a category field to books for fiction, non-fiction, etc.

For example, to add a GUI using tkinter, you’d need to install tkinter (it’s included with Python) and rewrite the interface. Here’s a simple example to get you started:

import tkinter as tk
from tkinter import messagebox

def add_book_gui():
    title = title_entry.get()
    author = author_entry.get()
    isbn = isbn_entry.get()
    year = year_entry.get()
    if title and author and isbn and year:
        add_book(title, author, isbn, int(year))
        messagebox.showinfo("Success", f"Book '{title}' added!")
    else:
        messagebox.showerror("Error", "Please fill all fields!")

root = tk.Tk()
root.title("Library Management System")
tk.Label(root, text="Title").pack()
title_entry = tk.Entry(root)
title_entry.pack()
tk.Label(root, text="Author").pack()
author_entry = tk.Entry(root)
author_entry.pack()
tk.Label(root, text="ISBN").pack()
isbn_entry = tk.Entry(root)
isbn_entry.pack()
tk.Label(root, text="Publication Year").pack()
year_entry = tk.Entry(root)
year_entry.pack()
tk.Button(root, text="Add Book", command=add_book_gui).pack()
root.mainloop()

This creates a simple window to add books. You can expand it for other features!

Tips and Best Practices

Here are some tips to make your project shine:

  • Error Handling: Always check for invalid inputs (e.g., non-numeric years).
  • Data Validation: Validate emails using regex or libraries like email-validator.
  • Backup Database: Regularly back up library.db to avoid data loss.
  • Comments: Add comments to your code for clarity.
  • Modularize: Break your code into smaller functions for reusability.
  • Test Thoroughly: Test edge cases like issuing a book that’s already issued or deleting a non-existent member.

Common Issues and Fixes

Ran into a problem? Here’s a quick troubleshooting guide:

  • Database Locked Error: Ensure only one instance of the program is running, as SQLite doesn’t handle multiple connections well.
  • Invalid ID: When testing, use the exact book_id, member_id, or transaction_id printed by the program.
  • No Output: Check if library.db is created in the correct folder.
  • Fine Calculation Wrong: Ensure your system date is correct, as fine calculation depends on it.

Why This Project Rocks

This project is awesome because:

  • It’s practical: Libraries actually use systems like this.
  • It’s scalable: You can add more features like a GUI or web interface.
  • It’s educational: You learn Python, SQLite, and database concepts.
  • It’s impressive: Show it off in your college or job interviews!

Conclusion

Phew, that was a long journey, dosto! We’ve built an Advanced Library Management System in Python that can manage books, members, borrowing, returning, fines, and reports. You’ve got the complete source code, step-by-step explanations, and ideas to take it further. This project is perfect for learning, showcasing your skills, or even using in a real library (with some tweaks, of course). So, what are you waiting for? Fire up your editor, run the code, and start managing your virtual library. And if you add cool features like a GUI or web app, do share with us, yaar!

Happy coding, and keep learning! If you have questions or want to add more features, drop a comment or ping me. Abhi ke liye, bas itna hi—chalo, thodi si chai peete hai!

Next Post Previous Post
No Comment
Add Comment
comment url