Database Construction - Python Programming Exercise

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 information in a SQLite database. 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

Database Construction

 Objective

Develop a Python program to create a utility that asks the user for data about books (title, author, genre, and summary) and stores this information in a SQLite database.

 Example Python Exercise

 Copy Python Code
import sqlite3

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 and create the table if necessary."""
        self.db_name = db_name
        self.connection = sqlite3.connect(self.db_name)
        self.cursor = self.connection.cursor()
        self._create_table()

    def _create_table(self):
        """Create the books table if it does not exist."""
        self.cursor.execute("""
            CREATE TABLE IF NOT EXISTS books (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                title TEXT NOT NULL,
                author TEXT NOT NULL,
                genre TEXT NOT NULL,
                summary TEXT NOT NULL
            )
        """)
        self.connection.commit()

    def add_book(self, book):
        """Add a new 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 get_book_data():
    """Prompt the user for book data."""
    title = input("Enter book title: ")
    author = input("Enter book author: ")
    genre = input("Enter book genre: ")
    summary = input("Enter book summary: ")
    return Book(title, author, genre, summary)


# Test Program
if __name__ == "__main__":
    # Initialize the database
    db = BookDatabase()

    # Ask the user to input a book's information
    print("Please enter information for a new book:")
    new_book = get_book_data()
    
    # Add the new book to the database
    db.add_book(new_book)
    print("\nBook added successfully!\n")

    # Ask the user if they want to add another book
    while True:
        add_another = input("Do you want to add another book? (y/n): ").lower()
        if add_another == 'y':
            new_book = get_book_data()
            db.add_book(new_book)
            print("\nBook added successfully!\n")
        elif add_another == 'n':
            break
        else:
            print("Invalid input. Please enter 'y' for yes or 'n' for no.")

    # Retrieve and display all books in the database
    print("\nBooks in the database:")
    books = db.get_all_books()
    for book in books:
        print(book)
    
    # Close the database connection
    db.close()

 Output

Please enter information for a new book:
Enter book title: The Great Gatsby
Enter book author: F. Scott Fitzgerald
Enter book genre: Fiction
Enter book summary: A story about Jay Gatsby's obsession with Daisy Buchanan.

Book added successfully!

 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 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...

  •  Complete Database Access

    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 ex...