לדלג לתוכן

8.1 מסד נתונים פתרון

הספרייה

import sqlite3

class Library:
    def __init__(self, db_name):
        self.conn = sqlite3.connect(db_name)
        self.cursor = self.conn.cursor()
        self.create_books_table()

    def create_books_table(self):
        self.cursor.execute('''CREATE TABLE IF NOT EXISTS books (
                                id INTEGER PRIMARY KEY,
                                title TEXT NOT NULL,
                                author TEXT NOT NULL,
                                available INTEGER DEFAULT 1)''')
        self.conn.commit()

    def add_book(self, title, author):
        self.cursor.execute("INSERT INTO books (title, author) VALUES (?, ?)", (title, author))
        self.conn.commit()
        print("Book added successfully.")

    def search_books(self, title=None, author=None):
        query = "SELECT * FROM books WHERE available = 1"
        if title:
            query += f" AND title LIKE '%{title}%'"
        if author:
            query += f" AND author LIKE '%{author}%'"
        self.cursor.execute(query)
        books = self.cursor.fetchall()
        if not books:
            print("No matching books found.")
        else:
            print("Matching books:")
            for book in books:
                print(book)

    def borrow_book(self, book_id):
        self.cursor.execute("UPDATE books SET available = 0 WHERE id = ?", (book_id,))
        self.conn.commit()
        print("Book borrowed successfully.")

    def return_book(self, book_id):
        self.cursor.execute("UPDATE books SET available = 1 WHERE id = ?", (book_id,))
        self.conn.commit()
        print("Book returned successfully.")

    def display_available_books(self):
        self.cursor.execute("SELECT * FROM books WHERE available = 1")
        books = self.cursor.fetchall()
        if not books:
            print("No available books.")
        else:
            print("Available books:")
            for book in books:
                print(book)

def main():
    library = Library('library.db')
    while True:
        print("\nLibrary Management System")
        print("1. Add Book")
        print("2. Search Books")
        print("3. Borrow Book")
        print("4. Return Book")
        print("5. Display Available Books")
        print("6. Exit")
        choice = input("Enter your choice: ")

        if choice == '1':
            title = input("Enter the title of the book: ")
            author = input("Enter the author of the book: ")
            library.add_book(title, author)

        elif choice == '2':
            title = input("Enter the title of the book (leave blank to skip): ")
            author = input("Enter the author of the book (leave blank to skip): ")
            library.search_books(title, author)

        elif choice == '3':
            book_id = input("Enter the ID of the book to borrow: ")
            library.borrow_book(book_id)

        elif choice == '4':
            book_id = input("Enter the ID of the book to return: ")
            library.return_book(book_id)

        elif choice == '5':
            library.display_available_books()

        elif choice == '6':
            print("Exiting...")
            break

        else:
            print("Invalid choice. Please try again.")

if __name__ == "__main__":
    main()
  • שימו לב שהפתרון הזה הוא ללא יצירת מחלקה של Book, זה פתרון פשוט יותר אך ממש את הרעיון של התממשקות מול הDB.
  • שימו לב שגם פה לא השתמשתי בORM, שזה גורם לקוד להיראות פחות טוב ופחות יפה.