wriye an python program to create a simple database. Aassume we are creating database of…
- User
wriye an python program to create a simple database. Aassume we are creating database of movies.
- Assistant
wriye an python program to create a simple database. Aassume we are creating database of movies.
Creating a simple database for movies in Python can be done using the SQLite database, which is built into Python as part of the standard library. Below is an example of a Python program that creates a simple database for movies using SQLite.
import sqlite3
# Connect to SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('movies.db')
# Create a cursor object to interact with the database
cursor = conn.cursor()
# Create a table for movies
cursor.execute('''
CREATE TABLE IF NOT EXISTS movies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
director TEXT,
year INTEGER,
genre TEXT
)
''')
# Insert some sample data into the movies table
sample_movies = [
('The Shawshank Redemption', 'Frank Darabont', 1994, 'Drama'),
('The Godfather', 'Francis Ford Coppola', 1972, 'Crime'),
('The Dark Knight', 'Christopher Nolan', 2008, 'Action'),
('Pulp Fiction', 'Quentin Tarantino', 1994, 'Crime'),
('The Lord of the Rings: The Return of the King', 'Peter Jackson', 2003, 'Adventure'),
]
cursor.executemany('''
INSERT INTO movies (title, director, year, genre)
VALUES (?, ?, ?, ?)
''', sample_movies)
# Commit the changes to the database
conn.commit()
# Function to display the movies in the database
def display_movies():
cursor.execute('SELECT * FROM movies')
movies = cursor.fetchall()
for movie in movies:
print(movie)
# Call the function to display the movies
print("List of Movies in the Database:")
display_movies()
# Close the database connection
conn.close()
SQLite Connection: We use the sqlite3.connect() to create a connection to a database file named movies.db. If this file doesn't exist, it will be created.
Cursor: We create a cursor object using conn.cursor(). This object is used to execute SQL commands.
Table Creation: We use SQL to create a new table named movies. This table has fields for id, title, director, year, and genre.
Inserting Data: We insert some sample movie data into the table using executemany(), which allows multiple records to be inserted at once.
Committing Changes: We save the changes to the database with conn.commit().
Displaying Data: There's a function display_movies() that queries the movies table and prints all records.
Closing Connection: Finally, we close the connection using conn.close(). This is important to ensure all resources are properly released.
This script provides a simple framework to create and manipulate a movie database using SQLite in Python. You can expand on this by adding more functionality, such as deleting records, updating existing records, or querying movies by specific criteria.