HOSPITAL MANAGEMENT
HOSPITAL MANAGEMENT
Python is a powerful and versatile coding language that's gaining popularity among developers
everywhere. Whether you're just getting started in programming or looking to add Python to your
existing skillset, understanding the basics of this code can be beneficial for any tech-savvy
individual. In this blog post, we'll explore what makes Python such an important tool and answer
the question: What is Python? If you're interested in learning Python, we recommend checking
out a Python beginner course. We'll also provide some helpful resources for those who want to
hone their skills and get better at writing with it. Get ready – you may find yourself wanting to
learn more about Python after diving into all it has to offer!
What is Python?
Python is a programming language that was created between the year of 1985 to 1990 by Dutch
developer Guido van Rossum. Python is an interpreted, object-oriented, high-level language with
dynamic semantics. Python is a garbage-collected and dynamic-typed programming language. It
offers strong support for integration with other languages and tools, comes with a large standard
library, and can be used for scripting, graphical user interfaces, web applications, game
development, and much more.
As one of the world's most popular coding languages, python is used by organizations such as
Google and Facebook; it's also popular among data scientists to make analysis easier. Python
provides large frameworks like Django, Flask, and Pyramid which are very helpful in developing
modern digital web applications rapidly. With its user-friendly syntax and cross-platform
compatibility, python has become increasingly essential in the software development industry.
The source code of the Python programming language is available under GNU's general public
license.
Python applications
There are various Python applications in the field of programming, those are
Python programming language supports structural and functional programming methods as well
as object-oriented programming methods.
Applications of python programming help to build large applications python can be used as a
scripting language or can be compiled into byte code.
1
Python supports dynamic type checking and it provides very high-level dynamic data types.
This particular programming language supports automatic garbage collection.
Python programming language can be easily integrated with C, C++, Java, COM, CORBA, and
ActiveX.
Python Jobs
Python is a very highly demanding language and Python programmers develop websites,
applications, and software components with the help of AI, data science, and ML technologies.
Python developer jobs and python jobs for freshers are very demanding in the field of IT.
Nowadays a Python developer can easily earn 150,000$ with 3-5 years of experience. This salary
and python career opportunities vary depending on the location. There are many big companies
using python, and those are
Google
Intel
Facebook
IBM
NASA
PayPal
Pinterest
2
Uber
Amazon
Netflix
And many more
Characteristics of Python
Easy-to-learn − Python has a simple structure, few keywords, and a defined syntax which allows
the user to pick up the language easily.
Easy-to-read − The code of the python programming language is clearly defined and visible to
the eyes.
Interactive Mode − Python language supports interactive mode which assists the developer to do
interactive testing and debugging of snippets of code.
Portable − This programming language can run on various hardware platforms and it has the
same interface for all platforms.
Easy-to-maintain − The source code of python programming language is fairly easy to maintain
by its user as well as its developers.
A broad standard library − The bulk library of the python programming language is cross-
platform compatible and very portable on Windows, UNIX, and Macintosh.
GUI Programming − Python supports GUI applications that have a feature to create and port to
many libraries, system calls, and windows systems such as Macintosh, Windows MFC, and the
X Window system of Unix.
Scalable − Python programming language provides better support and structure for large
programs than shell scripting of another language.
Extendable − Users can add low-level modules those are enabled programmers to add or
customize their tools to be more efficient for the Python interpreter.
Databases − Python programming language provides interfaces to all major commercial
databases
MySQL Introduction
MySQL is a Relational Database Management System. It was originally founded and developed
in Sweden by David Axmark, Allan Larsson and Michael Widenius.
3
Characteristics of MySQL:
1. Cost: It is released under an open–source license and hence required no cost or payment for its
usage.
3. Ease of Use: It is a simple database system. It can be easily managed from the command line.
Several graphical interfaces are also available.
5. Data Types: It supports many data types to support different types of data. It also supports
fixed–length and variable–length records.
6. Security: It offers privilege and password system that is very flexible and secure. Passwords
are secure because all password traffic is encrypted at the time of connecting to a server.
7. Scalability and Limits: It can handle large databases. Some real life MySQL databases contain
50 million records, some have up to 60,000 tables and about 500,00,00,000 rows.
Constraints:
Constraints are certain types of restrictions on the data values that an attribute can have. They are
used to ensure the accuracy and reliability of data.
1. NOT NULL: Ensures that a column cannot have NULL values where NULL means missing/
unknown/not applicable value.
2. UNIQUE: Ensures that all the values in a column are distinct / unique.
4. PRIMARY KEY: The column which can uniquely identify each row or record in a table.
5. FOREIGN KEY: The column which refers to value of an attribute defined as primary key in
another table.
4
Categories of SQL Commands:
The SQL commands used for creating a database, deleting a database, providing keys such as
primary key, foreign key etc on tables are known as DDL commands.
These commands will work with table structure not on table data directly (indirectly may act on
table data)
The Query and Update commands on tables are referred as DML commands. A few examples for
DML commands in SQL are:
The commands which are used to control the access to databases and tables are referred as Data
Control Language or Transaction Control Language commands. A few examples for TCL
commands in SQL are:
5
2. REVOKE – To take back rights of transaction from a user
Patients Table:
o Columns: patient_id (auto-incremented), name, age, gender, phone, email
o The patient_id is the primary key.
Doctors Table:
o Columns: doctor_id (auto-incremented), name, specialization, phone, email
o The doctor_id is the primary key.
Appointments Table:
o Columns: appointment_id (auto-incremented), patient_id, doctor_id,
appointment_date, appointment_time
o Foreign keys: patient_id references patients(patient_id) and doctor_id references
doctors(doctor_id).
2. Database Connection
In the MAIN PROGRAM section, the program connects to the MySQL database using the
mysql.connector library. It uses the following credentials to establish the connection:
6
host='localhost'
user='root'
password='root'
database='hospital_management'
3. Functions
The program contains several functions, each corresponding to a specific task, such as adding or
updating records, scheduling appointments, and viewing data.
Patient Management:
add_patient: Adds a new patient to the patients table by inserting the given details (name,
age, gender, phone, email).
update_patient: Updates the details of an existing patient by specifying the patient_id and
providing any new details.
delete_patient: Deletes a patient and their associated appointments from the patients
table. The function first deletes appointments to satisfy the foreign key constraint.
view_patients: Retrieves and displays all patients from the patients table.
search_patient: Searches for a patient based on the name, age, or phone number.
view_patient_appointments: Shows all appointments for a given patient, including the
doctor's name, date, and time.
Doctor Management:
add_doctor: Adds a new doctor to the doctors table.
update_doctor: Updates the details of an existing doctor by specifying the doctor_id and
any new details.
delete_doctor: Deletes a doctor and their associated appointments from the doctors table.
Like the patient deletion, the function first deletes the appointments.
view_doctors: Retrieves and displays all doctors from the doctors table.
search_doctor: Searches for a doctor based on the name, specialization, or phone number.
view_doctor_appointments: Displays all appointments for a given doctor, including the
patient's name, date, and time.
7
Appointment Management:
schedule_appointment: Schedules a new appointment by inserting the patient_id,
doctor_id, appointment_date, and appointment_time into the appointments table.
cancel_appointment: Cancels an appointment by deleting the corresponding record from
the appointments table.
update_appointment: Updates an existing appointment's details, such as the patient,
doctor, date, and time, based on the provided appointment_id.
daily_appointments_report: Generates a report for a specific date by retrieving all
appointments for that date, including the patient's and doctor's names and the
appointment time.
view_appointments: Displays all appointments, showing the patient name, doctor name,
appointment date, and time.
5. Main Logic
Handling Input: The program takes inputs from the user for various operations, such as
adding or updating patient/doctor details, scheduling appointments, etc.
Error Handling: If the user tries to delete or update a record that doesn't exist (e.g.,
providing a non-existing patient_id or doctor_id), the program prints an error message.
Commit Changes: After performing an operation (e.g., inserting, updating, or deleting
records), the changes are committed to the database with conn.commit().
Conclusion
This Hospital Management System is designed to handle all basic operations related to managing
a hospital's patients, doctors, and appointments. It allows easy access to information and ensures
that operations like adding, updating, deleting, and viewing records are done efficiently using
SQL queries. The program is modular, with separate functions for each operation, making it easy
to maintain and extend.
9
Limitations
The Hospital Management System you have implemented is a solid foundation, but it does
have some limitations:
1. No Input Validation:
o The system lacks checks for valid inputs (e.g., ensuring that the age is a valid
number, phone numbers have correct formatting, dates are in the correct format).
o It doesn’t handle invalid or empty inputs gracefully, which could lead to errors or
unexpected behavior.
2. Error Handling:
o There is little error handling for database connection issues, invalid SQL queries,
or unexpected failures (e.g., what happens if the database connection fails or the
queries return errors).
o The program doesn't handle scenarios where the user tries to delete a record that
has associated data (besides appointments). For example, if a doctor or patient is
referenced elsewhere in the system, the delete function might fail.
3. Security Risks:
o The system uses basic SQL queries without prepared statements or parameterized
queries in some places, which may expose it to SQL injection attacks.
o Sensitive information such as passwords (if added) and emails are stored in plain
text without encryption.
4. Lack of Authentication:
o There is no authentication system (e.g., login, password) to secure access to the
system. This means anyone can run operations like adding, deleting, or modifying
data without restrictions.
5. Limited Reporting and Analysis:
o Reports are limited to daily appointment reports. There’s no support for more
comprehensive reports such as monthly, yearly, or patient treatment history.
o The system does not allow for tracking patient history, medication, or treatments,
which could be critical in a hospital environment.
Addressing these limitations would make the system more robust, secure, and user-friendly.
10
Queries to be Executed in MySQL
CREATE DATABASE hospital_management;
USE hospital_management;
CREATE TABLE patients (
patient_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255),
age INT,
gender VARCHAR(10),
phone VARCHAR(20),
email VARCHAR(255));
CREATE TABLE doctors (
doctor_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255),
specialization VARCHAR(255),
phone VARCHAR(20),
email VARCHAR(255));
CREATE TABLE appointments (
appointment_id INT PRIMARY KEY AUTO_INCREMENT,
patient_id INT,
doctor_id INT,
appointment_date DATE,
appointment_time TIME,
FOREIGN KEY (patient_id) REFERENCES patients(patient_id),
FOREIGN KEY (doctor_id) REFERENCES doctors(doctor_id));
11
MAIN PROGRAM
import mysql.connector
import datetime # Connect to the MySQL database
conn = mysql.connector.connect(
host='localhost',
user='root',
password='root',
database='hospital_management'
)
cursor = conn.cursor()
def add_patient(name, age, gender, phone, email):
sql = '''INSERT INTO patients (name, age, gender, phone, email) VALUES (%s, %s, %s, %s,
%s)'''
cursor.execute(sql, (name, age, gender, phone, email))
conn.commit()
print(f"Patient '{name}' added successfully.")
def update_patient(patient_id, name=None, age=None, gender=None, phone=None,
email=None):
sql = '''UPDATE patients SET '''
val = []
if name:
sql += 'name = %s, '
val.append(name)
if age:
sql += 'age = %s, '
val.append(age)
if gender:
sql += 'gender = %s, '
val.append(gender)
12
if phone:
sql += 'phone = %s, '
val.append(phone)
if email:
sql += 'email = %s, '
val.append(email)
sql = sql.rstrip(', ') + ' WHERE patient_id = %s'
val.append(patient_id)
cursor.execute(sql, tuple(val))
conn.commit()
if cursor.rowcount > 0:
print(f"Patient ID {patient_id} updated successfully.")
else:
print(f"Patient ID {patient_id} not found.")
def add_doctor(name, specialization, phone, email):
sql = '''INSERT INTO doctors (name, specialization, phone, email) VALUES (%s, %s, %s,
%s)'''
cursor.execute(sql, (name, specialization, phone, email))
conn.commit()
print(f"Doctor '{name}' added successfully.")
def update_doctor(doctor_id, name=None, specialization=None, phone=None, email=None):
sql = '''UPDATE doctors SET '''
val = []
if name:
sql += 'name = %s, '
val.append(name)
if specialization:
sql += 'specialization = %s, '
val.append(specialization)
13
if phone:
sql += 'phone = %s, '
val.append(phone)
if email:
sql += 'email = %s, '
val.append(email)
sql = sql.rstrip(', ') + ' WHERE doctor_id = %s'
val.append(doctor_id)
cursor.execute(sql, tuple(val))
conn.commit()
if cursor.rowcount > 0:
print(f"Doctor ID {doctor_id} updated successfully.")
else:
print(f"Doctor ID {doctor_id} not found.")
def schedule_appointment(patient_id, doctor_id, appointment_date, appointment_time):
sql = '''INSERT INTO appointments (patient_id, doctor_id, appointment_date,
appointment_time)
VALUES (%s, %s, %s, %s)'''
cursor.execute(sql, (patient_id, doctor_id, appointment_date, appointment_time))
conn.commit()
print("Appointment scheduled successfully.")
def cancel_appointment(appointment_id):
sql = '''DELETE FROM appointments WHERE appointment_id = %s'''
cursor.execute(sql, (appointment_id,))
conn.commit()
if cursor.rowcount > 0:
print(f"Appointment ID {appointment_id} canceled successfully.")
else:
print(f"Appointment ID {appointment_id} not found.")
14
def view_patients():
sql = '''SELECT * FROM patients'''
cursor.execute(sql)
results = cursor.fetchall()
if not results:
print("No patients found.")
else:
print("Patients:")
for row in results:
print(f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}, Gender: {row[3]}, Phone:
{row[4]}, Email: {row[5]}")
def view_doctors():
sql = '''SELECT * FROM doctors'''
cursor.execute(sql)
results = cursor.fetchall()
if not results:
print("No doctors found.")
else:
print("Doctors:")
for row in results:
print(f"ID: {row[0]}, Name: {row[1]}, Specialization: {row[2]}, Phone: {row[3]},
Email: {row[4]}")
15
conditions.append(f'%{name}%')
if age:
sql += ' AND age = %s'
conditions.append(age)
if phone:
sql += ' AND phone LIKE %s'
conditions.append(f'%{phone}%')
cursor.execute(sql, tuple(conditions))
results = cursor.fetchall()
if not results:
print("No patients found.")
else:
print("Patients Found:")
for row in results:
print(f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}, Gender: {row[3]}, Phone:
{row[4]}, Email: {row[5]}")
cursor.execute(sql, tuple(conditions))
results = cursor.fetchall()
if not results:
print("No doctors found.")
else:
print("Doctors Found:")
for row in results:
print(f"ID: {row[0]}, Name: {row[1]}, Specialization: {row[2]}, Phone: {row[3]},
Email: {row[4]}")
def view_patient_appointments(patient_id):
sql = '''SELECT appointments.appointment_id, doctors.name AS doctor_name,
appointments.appointment_date, appointments.appointment_time
FROM appointments
JOIN doctors ON appointments.doctor_id = doctors.doctor_id
WHERE appointments.patient_id = %s'''
cursor.execute(sql, (patient_id,))
results = cursor.fetchall()
if not results:
print(f"No appointments found for Patient ID {patient_id}.")
else:
print(f"Appointments for Patient ID {patient_id}:")
for row in results:
print(f"Appointment ID: {row[0]}, Doctor: {row[1]}, Date: {row[2]}, Time: {row[3]}")
def view_doctor_appointments(doctor_id):
sql = '''SELECT appointments.appointment_id, patients.name AS patient_name,
appointments.appointment_date, appointments.appointment_time
FROM appointments
17
JOIN patients ON appointments.patient_id = patients.patient_id
WHERE appointments.doctor_id = %s'''
cursor.execute(sql, (doctor_id,))
results = cursor.fetchall()
if not results:
print(f"No appointments found for Doctor ID {doctor_id}.")
else:
print(f"Appointments for Doctor ID {doctor_id}:")
for row in results:
print(f"Appointment ID: {row[0]}, Patient: {row[1]}, Date: {row[2]}, Time: {row[3]}")
def delete_patient(patient_id):
# Deleting patient appointments first (due to foreign key constraint)
cursor.execute('''DELETE FROM appointments WHERE patient_id = %s''', (patient_id,))
conn.commit()
if cursor.rowcount > 0:
print(f"Patient ID {patient_id} and associated appointments deleted successfully.")
else:
print(f"Patient ID {patient_id} not found.")
def delete_doctor(doctor_id):
# Deleting doctor appointments first (due to foreign key constraint)
cursor.execute('''DELETE FROM appointments WHERE doctor_id = %s''', (doctor_id,))
conn.commit()
18
# Now delete the doctor
cursor.execute('''DELETE FROM doctors WHERE doctor_id = %s''', (doctor_id,))
conn.commit()
if cursor.rowcount > 0:
print(f"Doctor ID {doctor_id} and associated appointments deleted successfully.")
else:
print(f"Doctor ID {doctor_id} not found.")
def update_appointment(appointment_id, patient_id=None, doctor_id=None,
appointment_date=None, appointment_time=None):
sql = '''UPDATE appointments SET '''
val = []
if not results:
print(f"No appointments found for {date}.")
else:
print(f"Appointments for {date}:")
for row in results:
print(f"Appointment ID: {row[0]}, Patient: {row[1]}, Doctor: {row[2]}, Time:
{row[3]}")
20
def view_appointments():
sql = '''SELECT appointments.appointment_id, patients.name AS patient_name, doctors.name
AS doctor_name,
appointments.appointment_date, appointments.appointment_time
FROM appointments
JOIN patients ON appointments.patient_id = patients.patient_id
JOIN doctors ON appointments.doctor_id = doctors.doctor_id'''
cursor.execute(sql)
results = cursor.fetchall()
if not results:
print("No appointments found.")
else:
print("Appointments:")
for row in results:
print(f"ID: {row[0]}, Patient: {row[1]}, Doctor: {row[2]}, Date: {row[3]}, Time:
{row[4]}")
def main():
print("\nHospital Management System")
print("1. Add Patient")
print("2. Update Patient")
print("3. Add Doctor")
print("4. Update Doctor")
print("5. Schedule Appointment")
print("6. Cancel Appointment")
print("7. View Patients")
print("8. View Doctors")
print("9. View Appointments")
21
print("10. Search Patient")
print("11. Search Doctor")
print("12. View Patient Appointments")
print("13. View Doctor Appointments")
print("14. Delete Patient")
print("15. Delete Doctor")
print("16. Update Appointment")
print("17. Daily Appointments Report")
choice = input("Enter your choice: ")
if choice == '1':
name = input("Enter Patient Name: ")
age = int(input("Enter Patient Age: "))
gender = input("Enter Patient Gender: ")
phone = input("Enter Patient Phone: ")
email = input("Enter Patient Email: ")
add_patient(name, age, gender, phone, email)
elif choice == '2':
patient_id = int(input("Enter Patient ID to update: "))
name = input("Enter new Name (leave blank if no change): ")
age = input("Enter new Age (leave blank if no change): ")
gender = input("Enter new Gender (leave blank if no change): ")
phone = input("Enter new Phone (leave blank if no change): ")
email = input("Enter new Email (leave blank if no change): ")
update_patient(patient_id, name or None, age or None, gender or None, phone or None,
email or None)
elif choice == '3':
name = input("Enter Doctor Name: ")
specialization = input("Enter Doctor Specialization: ")
22
phone = input("Enter Doctor Phone: ")
email = input("Enter Doctor Email: ")
add_doctor(name, specialization, phone, email)
elif choice == '4':
doctor_id = int(input("Enter Doctor ID to update: "))
name = input("Enter new Name (leave blank if no change): ")
specialization = input("Enter new Specialization (leave blank if no change): ")
phone = input("Enter new Phone (leave blank if no change): ")
email = input("Enter new Email (leave blank if no change): ")
update_doctor(doctor_id, name or None, specialization or None, phone or None, email or
None)
elif choice == '5':
patient_id = int(input("Enter Patient ID: "))
doctor_id = int(input("Enter Doctor ID: "))
appointment_date = input("Enter Appointment Date (YYYY-MM-DD): ")
appointment_time = input("Enter Appointment Time (HH:MM:SS): ")
schedule_appointment(patient_id, doctor_id, appointment_date, appointment_time)
elif choice == '6':
appointment_id = int(input("Enter Appointment ID to cancel: "))
cancel_appointment(appointment_id)
elif choice == '7':
view_patients()
elif choice == '8':
view_doctors()
elif choice == '9':
view_appointments()
elif choice == '10':
name = input("Enter Patient Name to search (or leave blank): ")
age = input("Enter Patient Age to search (or leave blank): ")
23
phone = input("Enter Patient Phone to search (or leave blank): ")
search_patient(name or None, age or None, phone or None)
elif choice == '11':
name = input("Enter Doctor Name to search (or leave blank): ")
specialization = input("Enter Doctor Specialization to search (or leave blank): ")
phone = input("Enter Doctor Phone to search (or leave blank): ")
search_doctor(name or None, specialization or None, phone or None)
elif choice == '12':
patient_id = int(input("Enter Patient ID to view appointments: "))
view_patient_appointments(patient_id)
elif choice == '13':
doctor_id = int(input("Enter Doctor ID to view appointments: "))
view_doctor_appointments(doctor_id)
elif choice == '14':
patient_id = int(input("Enter Patient ID to delete: "))
delete_patient(patient_id)
elif choice == '15':
doctor_id = int(input("Enter Doctor ID to delete: "))
delete_doctor(doctor_id)
elif choice == '16':
appointment_id = int(input("Enter Appointment ID to update: "))
# Prompt for other details. Use default None if the user doesn't provide a value.
patient_id = input("Enter new Patient ID (leave blank if no change): ")
if patient_id == '':
patient_id = None
else:
patient_id = int(patient_id)
24
doctor_id = input("Enter new Doctor ID (leave blank if no change): ")
if doctor_id == '':
doctor_id = None
else:
doctor_id = int(doctor_id)
if _name_ == "_main_":
main()
25
OUTPUT 1
26
OUTPUT 2
27
OUTPUT 3
28
OUTPUT 4
29
OUTPUT 5
30
OUTPUT 6
31
OUTPUT 7
OUTPUT 8
32
OUTPUT 9
OUTPUT 10
33
OUTPUT 11
OUTPUT 12
34
OUTPUT 13
35
OUTPUT 14
36
OUTPUT 15
37
OUTPUT 16
38
OUTPUT 17
39
Hardware And Software Requirements
To develop and run a Python program with MySQL connectivity, you will need to ensure that
your system meets certain hardware and software requirements. Below are the typical hardware
and software requirements:
Hardware Requirements:
1. Processor:
• Minimum: 1.2 GHz processor (Intel or AMD)
• Recommended: 2.0 GHz or higher (multi-core processor for improved performance,
especially for larger applications)
2. RAM:
• Minimum: 2 GB of RAM
• Recommended: 4 GB or more (especially for larger datasets or concurrent database
operations)
3. Disk Space:
• Minimum: 500 MB of free disk space for installing Python, MySQL, and related
packages.
• Recommended: 2 GB or more if you're working with large datasets or multiple databases.
4. Network:
• If you're connecting to a remote MySQL server, ensure you have a stable network
connection with reasonable bandwidth for database queries.
Software Requirements:
1. Operating System:
• Windows (7/8/10/11)
• Linux (Ubuntu, CentOS, Debian, etc.)
• macOS (10.x or newer)
Python Version:t
• Minimum: Python 3.6 or higher (Python 3.8 or 3.10 recommended for better support and
performance)
• You can check your Python version with the command: python --version
2. MySQL Version:
40
• Minimum: MySQL 5.7 or higher (or MariaDB if using a compatible variant)
Ensure MySQL server is installed, either locally or remotely.
3. MySQL Connector for Python:
• You need the MySQL connector package to allow Python to connect to MySQL. You can
install this via pip:
• pip install mysql-connector-python
Alternatively, you can use other libraries like PyMySQL:
pip install pymysql
4. Database Management System (DBMS) Software:
• MySQL Workbench (or another database GUI) for easy management and visualization of
MySQL databases (optional but helpful).
5. Text Editor/IDE:
• Visual Studio Code (recommended for Python development, supports extensions for
Python and MySQL)
• PyCharm (Python-specific IDE, good for large projects)
• Sublime Text or Atom (lightweight text editors for Python)
• Alternatively, you can use any text editor of your choice.
41