w3resource

Python - Basic Movie Database: Add, Edit, Delete, and View Movies


Basic Movie Database: Create a simple movie database with features like adding, editing, and deleting movies.

Input values:
Add a Movie: Movie title
Director
Year of release
Genre.

Edit a Movie:
Movie ID or title (to identify the movie to be edited)
New title, director, year of release, and/or genre (fields to be updated)
Delete a Movie:
Movie ID or title (to identify the movie to be deleted)
View Movies:
Option to view all movies or search by title, director, year, or genre
Output Values: Confirmation message after adding, editing, or deleting a movie.
List of movies when viewing or searching.
Error messages if any operations fail (e.g., movie not found, invalid input).

Examples:

Example 1: Adding a Movie
Input:
Title: "Inception"
Director: "Christopher Nolan"
Year of Release: 2010
Genre: "Science Fiction"
Output:
"Movie 'Inception' added successfully."

Example 2: Editing a Movie
Input:
Movie ID: 1
New Title: "Inception: The Dream"
New Director: (leave blank to keep the same)
New Year of Release: (leave blank to keep the same)
New Genre: (leave blank to keep the same)
Output:
"Movie with ID 1 updated successfully."

Example 3: Deleting a Movie
Input:
Movie ID: 1
Output:
"Movie with ID 1 deleted successfully."

Example 4: Viewing Movies
Input:
Option: View all movies
Output:
List of all movies in the database:
1. Inception, directed by Christopher Nolan, released in 2010, Genre: Science Fiction
2. The Matrix, directed by Lana Wachowski and Lilly Wachowski, released in 1999, Genre: Science Fiction

Example 5: Searching for a Movie
Input:
Search by Title: "Inception"
Output:
List of movies matching the search:
1. Inception, directed by Christopher Nolan, released in 2010, Genre: Science Fiction

Solution 1: Using a Python List of Dictionaries for the Movie Database

This solution uses a simple Python list of dictionaries to represent the movie database. Each dictionary contains information about a movie, such as its title, director, year of release, and genre.

Code:

# Solution 1: Using a list of dictionaries to manage the movie database

# Initialize an empty list to store movies
movies = []

# Function to add a movie
def add_movie(title, director, year, genre):
    # Each movie is represented as a dictionary
    movie = {
        "id": len(movies) + 1,  # Unique ID for the movie
        "title": title,
        "director": director,
        "year": year,
        "genre": genre
    }
    movies.append(movie)  # Add the movie to the list
    print(f"Movie '{title}' added successfully.")

# Function to edit a movie
def edit_movie(movie_id, new_title=None, new_director=None, new_year=None, new_genre=None):
    # Find the movie by its ID
    for movie in movies:
        if movie["id"] == movie_id:
            # Update fields only if new values are provided
            if new_title:
                movie["title"] = new_title
            if new_director:
                movie["director"] = new_director
            if new_year:
                movie["year"] = new_year
            if new_genre:
                movie["genre"] = new_genre
            print(f"Movie with ID {movie_id} updated successfully.")
            return
    print(f"Movie with ID {movie_id} not found.")

# Function to delete a movie
def delete_movie(movie_id):
    global movies
    # Create a new list without the movie to be deleted
    movies = [movie for movie in movies if movie["id"] != movie_id]
    print(f"Movie with ID {movie_id} deleted successfully.")

# Function to view all movies
def view_movies():
    if movies:
        for movie in movies:
            print(f"{movie['id']}. {movie['title']}, directed by {movie['director']}, "
                  f"released in {movie['year']}, Genre: {movie['genre']}")
    else:
        print("No movies in the database.")

# Function to search for movies by title
def search_movie_by_title(title):
    found_movies = [movie for movie in movies if title.lower() in movie["title"].lower()]
    if found_movies:
        for movie in found_movies:
            print(f"{movie['id']}. {movie['title']}, directed by {movie['director']}, "
                  f"released in {movie['year']}, Genre: {movie['genre']}")
    else:
        print(f"No movies found with title '{title}'.")

# Example usage:
add_movie("Inception", "Christopher Nolan", 2010, "Science Fiction")
add_movie("The Matrix", "Wachowski Sisters", 1999, "Science Fiction")
view_movies()
edit_movie(1, new_title="Inception: The Dream")
delete_movie(2)
view_movies()
search_movie_by_title("Inception")

Output:

Movie 'Inception' added successfully.
Movie 'The Matrix' added successfully.
1. Inception, directed by Christopher Nolan, released in 2010, Genre: Science Fiction
2. The Matrix, directed by Wachowski Sisters, released in 1999, Genre: Science Fiction
Movie with ID 1 updated successfully.
Movie with ID 2 deleted successfully.
1. Inception: The Dream, directed by Christopher Nolan, released in 2010, Genre: Science Fiction
1. Inception: The Dream, directed by Christopher Nolan, released in 2010, Genre: Science Fiction

Explanation:

  • Movies are stored in a list as dictionaries with fields like title, director, year, and genre.
  • Functions allow adding, editing, deleting, viewing, and searching movies.
  • Easy-to-understand structure but data is not persistent (only stored in memory).

Solution 2: Using SQLite Database for Persistent Storage

This solution uses SQLite, a lightweight relational database, to store movie data. This approach allows the data to be persistent across program executions.

Code:

# Solution 2: Using SQLite for persistent movie database storage
import sqlite3

# Connect to (or create) a database
conn = sqlite3.connect("movies.db")
cursor = conn.cursor()

# Create a table for movies
cursor.execute('''
CREATE TABLE IF NOT EXISTS movies (
    id INTEGER PRIMARY KEY,
    title TEXT,
    director TEXT,
    year INTEGER,
    genre TEXT
)
''')

# Function to add a movie
def add_movie(title, director, year, genre):
    cursor.execute("INSERT INTO movies (title, director, year, genre) VALUES (?, ?, ?, ?)",
                   (title, director, year, genre))
    conn.commit()
    print(f"Movie '{title}' added successfully.")

# Function to edit a movie
def edit_movie(movie_id, new_title=None, new_director=None, new_year=None, new_genre=None):
    movie = cursor.execute("SELECT * FROM movies WHERE id=?", (movie_id,)).fetchone()
    if movie:
        cursor.execute('''
            UPDATE movies SET title=?, director=?, year=?, genre=?
            WHERE id=?
        ''', (new_title or movie[1], new_director or movie[2], new_year or movie[3], new_genre or movie[4], movie_id))
        conn.commit()
        print(f"Movie with ID {movie_id} updated successfully.")
    else:
        print(f"Movie with ID {movie_id} not found.")

# Function to delete a movie
def delete_movie(movie_id):
    cursor.execute("DELETE FROM movies WHERE id=?", (movie_id,))
    conn.commit()
    print(f"Movie with ID {movie_id} deleted successfully.")

# Function to view all movies
def view_movies():
    cursor.execute("SELECT * FROM movies")
    movies = cursor.fetchall()
    if movies:
        for movie in movies:
            print(f"{movie[0]}. {movie[1]}, directed by {movie[2]}, released in {movie[3]}, Genre: {movie[4]}")
    else:
        print("No movies in the database.")

# Function to search for movies by title
def search_movie_by_title(title):
    cursor.execute("SELECT * FROM movies WHERE title LIKE ?", ('%' + title + '%',))
    movies = cursor.fetchall()
    if movies:
        for movie in movies:
            print(f"{movie[0]}. {movie[1]}, directed by {movie[2]}, released in {movie[3]}, Genre: {movie[4]}")
    else:
        print(f"No movies found with title '{title}'.")

# Example usage:
add_movie("Inception", "Christopher Nolan", 2010, "Science Fiction")
add_movie("The Matrix", "Wachowski Sisters", 1999, "Science Fiction")
view_movies()
edit_movie(1, new_title="Inception: The Dream")
delete_movie(2)
view_movies()
search_movie_by_title("Inception")

# Close the connection when done
conn.close()

Output:

 Movie 'Inception' added successfully.
Movie 'The Matrix' added successfully.
1. Inception: The Dream, directed by Christopher Nolan, released in 2010, Genre: Science Fiction
2. Inception, directed by Christopher Nolan, released in 2010, Genre: Science Fiction
3. The Matrix, directed by Wachowski Sisters, released in 1999, Genre: Science Fiction
Movie with ID 1 updated successfully.
Movie with ID 2 deleted successfully.
1. Inception: The Dream, directed by Christopher Nolan, released in 2010, Genre: Science Fiction
3. The Matrix, directed by Wachowski Sisters, released in 1999, Genre: Science Fiction
1. Inception: The Dream, directed by Christopher Nolan, released in 2010, Genre: Science Fiction.

Explanation:

  • A SQLite database is used to store movies persistently.
  • The database has a table called movies with columns like title, director, year, and genre.
  • SQL queries handle adding, editing, deleting, and searching movies.
  • Data is stored on disk and can be retrieved even after restarting the program.


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/projects/python/python-project-basic-movie-database.php