Complete Database Access - Python Programming Exercise

In this exercise, you will develop a Python program to create a utility that allows the user to enter information about books and browse the existing data. This exercise is perfect for practicing file handling, database management, and user interaction in Python. By implementing this program, you will gain hands-on experience in handling file operations, database management, and user interaction in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Working with Relational Databases

 Exercise

Complete Database Access

 Objective

Develop a Python program to create a utility that allows the user to enter information about books and browse the existing data. The program should handle the case where the data file does not exist when the program starts.

 Example Python Exercise

 Copy Python Code
import sqlite3
import os

class Book:
    """Represents a book with a title, author, genre, and summary."""
    
    def __init__(self, title, author, genre, summary):
        """Initialize the book with title, author, genre, and summary."""
        self.title = title
        self.author = author
        self.genre = genre
        self.summary = summary

    def __str__(self):
        """Return a string representation of the book."""
        return f"Title: {self.title}\nAuthor: {self.author}\nGenre: {self.genre}\nSummary: {self.summary}\n"


class BookDatabase:
    """Manages a database of books."""
    
    def __init__(self, db_name="books.db"):
        """Initialize the database connection."""
        self.db_name = db_name
        self.connection = sqlite3.connect(self.db_name)
        self.cursor = self.connection.cursor()
        self.create_table_if_not_exists()

    def create_table_if_not_exists(self):
        """Create the books table if it doesn't exist."""
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS books (
                title TEXT,
                author TEXT,
                genre TEXT,
                summary TEXT
            )
        ''')
        self.connection.commit()

    def add_book(self, book):
        """Add a book to the database."""
        self.cursor.execute('''
            INSERT INTO books (title, author, genre, summary)
            VALUES (?, ?, ?, ?)
        ''', (book.title, book.author, book.genre, book.summary))
        self.connection.commit()

    def get_all_books(self):
        """Retrieve all books from the database."""
        self.cursor.execute("SELECT title, author, genre, summary FROM books")
        rows = self.cursor.fetchall()
        return [Book(title, author, genre, summary) for title, author, genre, summary in rows]

    def close(self):
        """Close the database connection."""
        self.connection.close()


def display_books(db):
    """Display all books stored in the database."""
    books = db.get_all_books()
    
    if not books:
        print("No books found in the database.")
    else:
        print("\nBooks stored in the database:\n")
        for book in books:
            print(book)


def add_book_to_db(db):
    """Allow the user to input information about a book and add it to the database."""
    print("\nEnter the details of the new book:")
    title = input("Title: ")
    author = input("Author: ")
    genre = input("Genre: ")
    summary = input("Summary: ")
    
    new_book = Book(title, author, genre, summary)
    db.add_book(new_book)
    print("\nBook added to the database!")


def main():
    """Main function to run the program."""
    db = BookDatabase()

    while True:
        print("\nBook Database Utility")
        print("1. Display all books")
        print("2. Add a new book")
        print("3. Exit")
        
        choice = input("Enter your choice: ")
        
        if choice == "1":
            display_books(db)
        elif choice == "2":
            add_book_to_db(db)
        elif choice == "3":
            print("Exiting program.")
            break
        else:
            print("Invalid choice. Please try again.")

    db.close()


# Run the program
if __name__ == "__main__":
    main()

 Output

Book Database Utility
1. Display all books
2. Add a new book
3. Exit
Enter your choice: 1

Books stored in the database:

Title: The Great Gatsby
Author: F. Scott Fitzgerald
Genre: Fiction
Summary: A story about Jay Gatsby's obsession with Daisy Buchanan.

 Share this Python Exercise

 More Python Programming Exercises of Working with Relational Databases

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Database Construction

    In this exercise, you will develop a Python program to create a utility that asks the user for data about books (title, author, genre, and summary) and stores this in...

  •  Database Querying

    In this exercise, you will develop a Python program to create a utility that displays the data about books which your previous program has stored. This exercise...