Here’s the corrected text:
This Database Exercise Project will help Python developers to learn database programming skills quickly. In this exercise, we will perform database CRUD operations using Python.
Also Read:
Note:
This exercise covers the following three popular database servers. You can choose the database server you are familiar with to solve this exercise.
- MySQL
- PostgreSQL
- SQLite
You can use any driver (DB module) as per your wish, for example, there are more than 5 libraries are available to communicate with MySQL. In this exercise, I am using the following libraries.
- MySQL: mysql connector python
- PostgreSQL: psycopg2
- SQLite: sqlite3
This Python database programming exercise includes: –
Here’s the corrected text:
Now it has 5 exercise questions, which simulate real-time queries, and each question contains a specific skill you need to learn. When you complete the exercise, you will become more familiar with database operations in Python.
Note:
The solution is provided at the end of each question. There are also tips and helpful learning resources for each question, which will help you solve the exercise.
Exercise/mini Project: Hospital Information System
In this exercise, We are implementing the Hospital Information System. In this exercise, I have created two tables, Hospital and Doctor. You need to create those two tables on your database server before starting the exercise.
SQL Queries for data preparation
Please find below the SQL queries to prepare the required data for our exercise.
MySQL
Create Database
CREATE database python_db;Code language: Python (python)Create Hospital Table
CREATE TABLE Hospital (
Hospital_Id INT UNSIGNED NOT NULL,
Hospital_Name TEXT NOT NULL,
Bed_Count INT,
PRIMARY KEY (Hospital_Id)
);
INSERT INTO Hospital (Hospital_Id, Hospital_Name, Bed_Count)
VALUES
('1', 'Mayo Clinic', 200),
('2', 'Cleveland Clinic', 400),
('3', 'Johns Hopkins', 1000),
('4', 'UCLA Medical Center', 1500);Code language: Python (python)Create Doctor Table
CREATE TABLE Doctor(
Doctor_Id INT UNSIGNED NOT NULL,
Doctor_Name TEXT NOT NULL,
Hospital_Id INT NOT NULL,
Joining_Date DATE NOT NULL,
Speciality TEXT NULL,
Salary INT NULL,
Experience INT NULL,
PRIMARY KEY (Doctor_Id)
);
INSERT INTO Doctor (Doctor_Id, Doctor_Name, Hospital_Id, Joining_Date, Speciality, Salary, Experience)
VALUES
('101', 'David', '1', '2005-2-10', 'Pediatric', '40000', NULL),
('102', 'Michael', '1', '2018-07-23', 'Oncologist', '20000', NULL),
('103', 'Susan', '2', '2016-05-19', 'Garnacologist', '25000', NULL),
('104', 'Robert', '2', '2017-12-28', 'Pediatric ', '28000', NULL),
('105', 'Linda', '3', '2004-06-04', 'Garnacologist', '42000', NULL),
('106', 'William', '3', '2012-09-11', 'Dermatologist', '30000', NULL),
('107', 'Richard', '4', '2014-08-21', 'Garnacologist', '32000', NULL),
('108', 'Karen', '4', '2011-10-17', 'Radiologist', '30000', NULL);Code language: Python (python)PostgreSQL
Create Database
CREATE database python_db;Code language: Python (python)Create Hospital Table
CREATE TABLE Hospital (
Hospital_Id serial NOT NULL PRIMARY KEY,
Hospital_Name VARCHAR (100) NOT NULL,
Bed_Count serial
);
INSERT INTO Hospital (Hospital_Id, Hospital_Name, Bed_Count)
VALUES
('1', 'Mayo Clinic', 200),
('2', 'Cleveland Clinic', 400),
('3', 'Johns Hopkins', 1000),
('4', 'UCLA Medical Center', 1500);Code language: Python (python)Create Doctor Table
CREATE TABLE Doctor (
Doctor_Id serial NOT NULL PRIMARY KEY,
Doctor_Name VARCHAR (100) NOT NULL,
Hospital_Id serial NOT NULL,
Joining_Date DATE NOT NULL,
Speciality VARCHAR (100) NOT NULL,
Salary INTEGER NOT NULL,
Experience SMALLINT
);
INSERT INTO Doctor (Doctor_Id, Doctor_Name, Hospital_Id, Joining_Date, Speciality, Salary, Experience)
VALUES
('101', 'David', '1', '2005-2-10', 'Pediatric', '40000', NULL),
('102', 'Michael', '1', '2018-07-23', 'Oncologist', '20000', NULL),
('103', 'Susan', '2', '2016-05-19', 'Garnacologist', '25000', NULL),
('104', 'Robert', '2', '2017-12-28', 'Pediatric ', '28000', NULL),
('105', 'Linda', '3', '2004-06-04', 'Garnacologist', '42000', NULL),
('106', 'William', '3', '2012-09-11', 'Dermatologist', '30000', NULL),
('107', 'Richard', '4', '2014-08-21', 'Garnacologist', '32000', NULL),
('108', 'Karen', '4', '2011-10-17', 'Radiologist', '30000', NULL);Code language: Python (python)SQLite
Create Database
CREATE database python_db;Code language: Python (python)Create Hospital Table
CREATE TABLE Hospital (
Hospital_Id INTEGER NOT NULL PRIMARY KEY,
Hospital_Name TEXT NOT NULL,
Bed_Count INTEGER NOT NULL
);
INSERT INTO Hospital (Hospital_Id, Hospital_Name, Bed_Count)
VALUES
('1', 'Mayo Clinic', 200),
('2', 'Cleveland Clinic', 400),
('3', 'Johns Hopkins', 1000),
('4', 'UCLA Medical Center', 1500);Code language: Python (python)Create Doctor Table
CREATE TABLE Doctor (
Doctor_Id INTEGER NOT NULL PRIMARY KEY,
Doctor_Name TEXT NOT NULL,
Hospital_Id INTEGER NOT NULL,
Joining_Date TEXT NOT NULL,
Speciality TEXT NOT NULL,
Salary INTEGER NOT NULL,
Experience INTEGER
);
INSERT INTO Doctor (Doctor_Id, Doctor_Name, Hospital_Id, Joining_Date, Speciality, Salary, Experience)
VALUES
('101', 'David', '1', '2005-2-10', 'Pediatric', '40000', NULL),
('102', 'Michael', '1', '2018-07-23', 'Oncologist', '20000', NULL),
('103', 'Susan', '2', '2016-05-19', 'Garnacologist', '25000', NULL),
('104', 'Robert', '2', '2017-12-28', 'Pediatric ', '28000', NULL),
('105', 'Linda', '3', '2004-06-04', 'Garnacologist', '42000', NULL),
('106', 'William', '3', '2012-09-11', 'Dermatologist', '30000', NULL),
('107', 'Richard', '4', '2014-08-21', 'Garnacologist', '32000', NULL),
('108', 'Karen', '4', '2011-10-17', 'Radiologist', '30000', NULL);Code language: Python (python)These tables should look like this.


SQL data model that we are using for this exercise

Now, let see the exercise questions.
Exercise 1: Connect to your database server and print its version
Reference article for help:
Note:
- Write SQL query to get the database server version.
- Connect to the database and use
cursor.execute()to execute this query. - Next, use
cursor.fetchone()to fetch the record.
Python MySQL Solution
Python PostgreSQL Solution
Python SQLite Solution
Question 2: Fetch Hospital and Doctor Information using hospital Id and doctor Id
Implement the functionality to read the details of a given doctor from the doctor table and Hospital from the hospital table. i.e., read records from Hospital and Doctor Table as per given hospital Id and Doctor Id.
Given:
def get_hospital_detail(hospital_id):
#Read data from Hospital table
def get_doctor_detail(doctor_id):
# Read data from Doctor table
get_hospital_details(2)
get_doctor_details(105)Code language: Python (python)Hint
- Connect to
python_dband usecursor.execute()to execute the parameterized query. - Next, use
cursor.fetchall()to fetch the record. - Next, iterate record/resultSet to print all column values
Expected Output
Question 2: Read given hospital and doctor details Printing Hospital record Hospital Id: 2 Hospital Name: Cleveland Clinic Bed Count: 400 Printing Doctor record Doctor Id: 105 Doctor Name: Linda Hospital Id: 3 Joining Date: 2004-06-04 Specialty: Garnacologist Salary: 42000 Experience: None
Reference article for help:
- How to use database parameterized query in Python.
- Python Select data from MySQL Table
- Python select from PostgreSQL Table
- Python Select from SQLite Table
Python MySQL Solution
Python PostgreSQL Solution
Python SQLite Solution
Exercise 3: Get the list Of doctors as per the given specialty and salary
Note: Fetch all doctors whose salary higher than the input amount and specialty is the same as the input specialty.
Given:
def get_specialist_doctors_list(speciality, salary):
#Fetch doctor's details as per Speciality and Salary
get_specialist_doctors_list("Garnacologist", 30000)Code language: Python (python)Hint
- Define the parameterized select query to fetch data from the table as per the given specialty and salary.
- Next, use the cursor.execute() to execute the query.
- Next, get all records using
cursor.fetchall() - Iterate those records and print each row.
Expected output
Printing doctors whose specialty is Garnacologist and salary greater than 30000 Doctor Id: 105 Doctor Name: Linda Hospital Id: 3 Joining Date: 2004-06-04 Specialty: Garnacologist Salary: 42000 Experience: None Doctor Id: 107 Doctor Name: Richard Hospital Id: 4 Joining Date: 2014-08-21 Specialty: Garnacologist Salary: 32000 Experience: None
Python MySQL Solution
Python PostgreSQL Solution
Python SQLite Solution
Exercise 4: Get a list of doctors from a given hospital
Note: Implement the functionality to fetch all the doctors as per the given Hospital Id. You must display the hospital name of a doctor.
Given:
def get_doctors(hospital_id):
#Fetch All doctors within given Hospital
get_doctors(2)
Code language: Python (python)
Hint:
- Define the parameterized select query to get the hospital name as per the given hospital id.
- Next, use the
cursor.execute()to execute this query and store the hospital name in a variable. - Define the parameterized select query to fetch all doctors from the doctor table as per the given hospital id.
- Next, use the
cursor.execute()to execute the query. - Next, get all records using
cursor.fetchall() - Iterate those records and print each column. Also, display the hospital name we fetched in the first query in each doctor’s entry
Python MySQL Solution
Python PostgreSQL Solution
Python SQLite Solution
Operation 5: Update doctor experience in years
The value of the experience column for each doctor is null. Implement the functionality to update the experience of a given doctor in years.
Given:
def def update_doctor_experience(doctor_id):
# Update Doctor Experience in Years
update_doctor_experience(101)Code language: Python (python)
Hint
- The doctor table has the joining date for each doctor.
- Get a given doctor’s joining date.
- To get a difference in a year, we can calculate the difference between today’s date and joining-date in years.
- After calculating the difference in a year, you can execute the update table query to update the experience of a given doctor.
Expected Output
Before:
Printing Doctor record Doctor Id: 101 Doctor Name: David Hospital Id: 1 Joining Date: 2005-02-10 Specialty: Pediatric Salary: 40000 Experience: None
After:
Printing Doctor record Doctor Id: 101 Doctor Name: David Hospital Id: 1 Joining Date: 2005-02-10 Specialty: Pediatric Salary: 40000 Experience: 15
Reference article for help:
- How to use database parameterized query in Python.
- Python update MySQL Table
- Python PostgreSQL CRUD Operations
- Python Update SQLite Table

Do you have examples using 2 phase commit? I use 2 different databases and need solution to the same. But I have no Python experience
I am into Java and recently using Python
This place is amazing! Thank you so much!
Thank you, Ben.
I am looking for help with this task I will post the requirements followed but the cod I have created until the point where I got stuck. Please If you have any idea how I should progress further don’t hesitate to help me. Thank you!
Programming for Databases
Develop Python code to implement a basic text-based application to allow the user to interact with the online electronics shopping database as outlined below. All students should complete questions a, b, and c below and to achieve a higher grade, also complete question d.
a. i. Prompt for the entry of a shopper_id which will be used to test all the menu options. If the shopper_id entered is found, print a welcome message including the name of the shopper. If the shopper_id is not found in the database, print an error message and exit the program otherwise print the main menu below.
ii. Print a text-based menu as follows:
ORINOCO – SHOPPER MAIN MENU
1. Display your order history
2. Add an item to your basket
3. View your basket
4. Change the quantity of an item in your basket
5. Remove an item from your basket
6. Checkout
7. Exit
iii. As shoppers should be able to resume a basket previously created from a previous execution of the program on the same day, check if there is a row in the shopper_baskets table created today for the selected shopper and, if so, make this the current basket otherwise create a new (empty) basket. If there is more than one basket created today for the shopper, use the most recent one.
You can use the following SQL query to return the most recent basket for the current shopper created today (if there is one):
SELECT basket_id
FROM shopper_baskets
WHERE shopper_id = ?
AND DATE(basket_created_date_time) = DATE(‘now’)
ORDER BY basket_created_date_time DESC
LIMIT 1
When you execute the query, pass the shopper_id as a parameter to replace the ? placeholder.
b. Implement menu options 1 and 7 as follows:
Option 1 – Display your order history
i. For each order that the customer has placed, display the order id and order date together with the product description, seller name, price, quantity ordered and status of each product on that order. You can use the query you wrote for Question 1b of this assessment as a basis for the SQL query for this option.
ii. Sort orders by order date (most recent first)
iii. If no orders are found for the shopper_id that you are testing with, print the message “No orders placed by this customer”
iv. Display the data in the format shown below (which is for shopper_id 10010)
v. Return to the main menu
Option 7 – Exit
i. Exit the program
c. Implement menu options 2 and 3 as follows:
Please note: The details of the shopper’s basket should be stored in the shopper_baskets and basket_contents tables and not in a Python data structure (like a list). This will allow a shopper to continue with their last basket if they didn’t complete the checkout in a previous execution of the program.
Option 2 – Add an item to your basket
i. Display a numbered list of product categories
ii. Prompt the user to enter the number of the product category they want to choose from and store the category_id for the selected category
iii. Display a numbered list of the available products in the category selected
iv. Prompt the user to enter the number of the product they want to purchase and store the product_id for the selected product
v. Display a numbered list of sellers who sell the product they have selected and the price they are selling that product at
vi. Prompt the user to enter the seller they wish to buy the product from and store the seller_id for the selected seller
vii. Prompt the user to enter the quantity of the selected product they want to order. Display ‘The quantity must be greater than 0’ if the quantity is len(option_list) or selected_option == 0:
prompt = “Enter the number against the “+type+” you want to choose: ”
selected_option = int(input(prompt))
return option_list[selected_option – 1]
This function should be called in steps i, iii and v above using a command of the following format:
id_of_selected_option = _display_options(query_rows,title,type)
query_rows must consist of two values – id and description i.e. the category_id and category_description
the title is some text to put above the list of options to act as a title
type is used to customize the prompt to make it appropriate for what you want the user to select
Option 3 – Display your basket
i. If the basket is empty, display ‘Your basket is empty otherwise display all rows from the basket_contents table for the current basket, labelling each item with a basket item no. starting at 1. Also, display a total basket cost.
An example of how the basket should be displayed is shown below:
ii. Return to the main menu
d. Implement the remaining menu options (4, 5 and 6) as follows:
Option 4 – Change the quantity of an item in your basket
i. If the basket is empty, display ‘Your basket is empty’ and return to the main menu otherwise display the current basket and the basket total (as per option 3.
ii. If there is more than one item in the basket, prompt the user to enter the basket item no. of the item they want to update. If they enter an invalid basket item no., display ‘The basket item no. you have entered is invalid’ and re-prompt the user to enter it again.
If there is only one item in the basket, this will obviously be the one the user wants to change.
iii. Prompt the user to enter the new quantity for the item selected.
If they enter a quantity = 1: print("{0:15} {1:15} {2:70} {3:21} {4:20} {5:15} {6:10}".format('Order number','Order data','Product description', 'Seller','Price','Quantity','Status')) for shopper_row in display: order_id = shopper_row[0] data = shopper_row[1] product = shopper_row[2] seller = shopper_row[3] price = shopper_row[4] quantity = shopper_row[5] status = shopper_row[6] print("\n{0:10}\t\t{1:15}{2:70}{3:25}£{4:10}{5:15}\t\t{6:10}".format(order_id, data, product,seller,price, quantity,status)) else: print("No orders placed by this customer") elif choose == 2: category_menu = "SELECT category_id,category_description\ FROM categories" cur.execute(category_menu) option_2 = cur.fetchall() if option_2: print("{0:30} ".format('Product Category')) for i in option_2: category_id = i[0] category_description =i[1] print("\n{0}.\t{1}".format(category_id,category_description)) category_option = input('\nEnter the number againts the product category You want to choose :\n') c_name = "SELECT p.product_description,p.product_id\ FROM categories c\ INNER JOIN products p ON c.category_id = p.category_id\ WHERE c.category_id = ?" cur.execute(c_name,(category_option,)) c_category = cur.fetchall() print("{0}".format('Products')) b = 0 for a in c_category: b=b+1 p_description = a[0] print("\n{0}.\t{1}".format(b,p_description)) product_option = input('\nEnter the number againts the product You want to choose : \n') seller_name="SELECT DISTINCT(s.seller_name),op.price,p.product_id\ FROM categories c\ INNER JOIN products p ON c.category_id = p.category_id\ INNER JOIN ordered_products op ON p.product_id = op.product_id\ INNER JOIN sellers s ON op.seller_id = s.seller_id\ WHERE c.category_id = 1 AND p.product_id = 3006033\ ORDER BY s.seller_name" cur.execute(seller_name,(product_option,)) a_category=cur.fetchall() print(a_category) print("{0}".format('Sellers who sell this product')) for d in a_category: seller_name= d[0] print("{0}".format(seller_name))Sorry, the full code is here and everything is working fine until option 2 where I have to get the
iv. Prompt the user to enter the number of the product they want to purchase and store the product_id for the selected product
v. Display a numbered list of sellers who sell the product they have selected and the price they are selling that product at
……
Hi, I´m relatively new to Python and SQL. (I’m using Postgres). And I have some suggestions:
In number 4 wouldnt be better to use JOIN method? Like :
In number5 I used:
And maybe for all exercises instead of printing rows like :
Is it good replacements?
Thank you very much for this content, I learned a lot!
Hey David, You can solve using your own way. Our approach is just an example. Thank you for uploading another solution.
Start a python dedicated Forum !
Thank you Vishal for loads of awesome content out here.
Do you have db exercise for oracle db as well pls?
Thank you Sudhakar, You can use the same exercise for Oracle
Hi, for your data for the doctor table, one of the entries for speciality was ‘Pediatric ‘, notice the space after the letter ‘c’ and another entry is ‘Pediatric’ with no space after the ‘c’. Is that intentional? It caught me a little bit off guard as to why my function wasn’t grabbing all the ‘Pediatric’ data.
Hey steven, it is not intentional, it is a mistake. you can edit table row and remove extra space. Thank you for commenting.
thank you very much
Why there is no Quiz on Database connectivity?
plz inform proper how to insert a form field data into Database.
Shweta thank you for your comment. It is altogether a different topic. I created this exercise solely for Database operations from Python. You can read values from the form field and then pass it to a function which will insert into the database.