D Dev Duniya
Back to Journal
8 min read

Student Management System with SQLAlchemy and Python

Ashish Yadav

Ashish Yadav

Published on Dev Duniya
Keep exploring
Compare the details before you buy.

Welcome to this comprehensive guide on building a Student Management System using SQLAlchemy and Python. This tutorial will take you from the basics to advanced features, allowing you to manage student data effectively. We will cover everything from setting up the database, creating models, and implementing CRUD operations to displaying data in a tabular format.

Prerequisites

Before we dive into the project, make sure you have the following:

  • Basic knowledge of Python.
  • Understanding of SQL and relational databases.
  • Python installed on your machine.
  • MySQL server set up.
  • Required Python libraries installed (sqlalchemy, pymysql, tabulate).

Setting Up the Project

Step 1: Install Required Libraries:

Open your terminal and install the required libraries using pip:

pip install sqlalchemy pymysql tabulate

Step 2: Set Up MySQL Database

Ensure your MySQL server is running and create a database for this project. You can use the following commands in your MySQL client:

CREATE DATABASE DatabaseName;

Step 3: Create the Project Structure

Organize your project files in a structured manner:

student_management_system/
├── main.py
└── models.py

Database Configuration and Models

Step 1: Database Configuration

In main.py, set up the database connection using SQLAlchemy:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "mysql+pymysql://USERNAME:PASSWORD@HOST/DATABASE"

engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Step 2: Define the Student Model

In models.py, define the Student model:

from sqlalchemy import Column, Integer, String, Date
from sqlalchemy.orm import declarative_base

Base = declarative_base()

class Student(Base):
    __tablename__ = 'students'
    roll_no = Column(Integer, primary_key=True, index=True)
    name = Column(String(50), nullable=False)
    class_name = Column(String(50), nullable=False)
    subjects = Column(String(200), nullable=False)
    gender = Column(String(10), nullable=False)
    dob = Column(Date, nullable=False)
    mobile_no = Column(String(15), nullable=False)
    address = Column(String(100), nullable=False)

Step 3: Create Tables

Back in main.py, create the tables:

from models import Base, engine

Base.metadata.create_all(bind=engine)

Implementing CRUD Operations

Add Student Function

In main.py, implement the function to add a student:

from models import Student
import datetime

def add_student(session, roll_no, name, class_name, subjects, gender, dob, mobile_no, address):
    dob_date = datetime.datetime.strptime(dob, '%Y-%m-%d').date()
    new_student = Student(roll_no=roll_no, name=name, class_name=class_name, subjects=subjects, gender=gender, dob=dob_date, mobile_no=mobile_no, address=address)
    session.add(new_student)
    session.commit()
    print(f"Student {name} added successfully.")

Remove Student Function

def remove_student(session, roll_no):
    student = session.query(Student).filter(Student.roll_no == roll_no).first()
    if student:
        session.delete(student)
        session.commit()
        print(f"Student {roll_no} removed successfully.")
    else:
        print(f"Student {roll_no} not found.")

Update Student Function

def update_student(session, roll_no, **kwargs):
    student = session.query(Student).filter(Student.roll_no == roll_no).first()
    if student:
        for key, value in kwargs.items():
            if hasattr(student, key):
                if key == 'dob':
                    value = datetime.datetime.strptime(value, '%Y-%m-%d').date()
                setattr(student, key, value)
        session.commit()
        print(f"Student {roll_no} updated successfully.")
    else:
        print(f"Student {roll_no} not found.")

Display Students Function

from tabulate import tabulate

def display_students(session):
    students = session.query(Student).all()
    if students:
        table = [[student.roll_no, student.name, student.class_name, student.subjects, student.gender, student.dob, student.mobile_no, student.address] for student in students]
        print(tabulate(table, headers=["Roll No", "Name", "Class", "Subjects", "Gender", "DOB", "Mobile No", "Address"], tablefmt="pretty"))
    else:
        print("No Students Found.")

Search Function

def search_student(session, search_term):
    students = session.query(Student).filter((Student.name.ilike(f'%{search_term}%')) | (Student.roll_no == search_term)).all()
    if students:
        table = [[student.roll_no, student.name, student.class_name, student.subjects, student.gender, student.dob, student.mobile_no, student.address] for student in students]
        print(tabulate(table, headers=["Roll No", "Name", "Class", "Subjects", "Gender", "DOB", "Mobile No", "Address"], tablefmt="pretty"))
    else:
        print("No Students Found.")

Validate Date Inputs

Implement input validation to ensure data integrity:

def validate_date(date_text):
    try:
        datetime.datetime.strptime(date_text, '%Y-%m-%d')
        return True
    except ValueError:
        return False

Main Program

Implement the main program loop to interact with the user:

def exit_program():
    print("Exiting Program.")
    exit()

def main():
    session = SessionLocal()
    while True:
        print("\nStudent Management System")
        print("1. Add Student")
        print("2. Remove Student")
        print("3. Update Student")
        print("4. Display Students")
        print("5. Exit Program")
        print("6. Search Student")
        choice = input("Enter your choice: ")
        if choice == "1":
            roll_no = int(input("Enter Roll No: "))
            name = input("Enter Name: ")
            class_name = input("Enter Class: ")
            subjects = input("Enter Subjects (comma-separated): ")
            gender = input("Enter Gender: ")
            dob = input("Enter DOB (YYYY-MM-DD): ")
            mobile_no = input("Enter Mobile No: ")
            address = input("Enter Address: ")
            add_student(session, roll_no, name, class_name, subjects, gender, dob, mobile_no, address)
        elif choice == "2":
            roll_no = int(input("Enter Roll No to remove: "))
            remove_student(session, roll_no)
        elif choice == "3":
            roll_no = int(input("Enter Roll No to update: "))
            fields = ['name', 'class_name', 'subjects', 'gender', 'dob', 'mobile_no', 'address']
            kwargs = {}
            for field in fields:
                value = input(f"Enter new {field} (or press Enter to skip): ")
                if value:
                    kwargs[field] = value
            update_student(session, roll_no, **kwargs)
        elif choice == "4":
            display_students(session)
        elif choice == "5":
            exit_program()
        elif choice == "6":
            search_term = input("Enter name or roll number to search: ")
            search_student(session, search_term)
        else:
            print("Invalid Choice. Please try again")

if __name__ == "__main__":
    main()

Complete Code

For your convenience, here is the complete code for the project:

model.py

# models.py
from sqlalchemy import Column, Integer, String, Date
from sqlalchemy.orm import declarative_base

Base = declarative_base()

class Student(Base):
    __tablename__ = 'students'
    roll_no = Column(Integer, primary_key=True, index=True)
    name = Column(String(50), nullable=False)
    class_name = Column(String(50), nullable=False)
    subjects = Column(String(200), nullable=False)
    gender = Column(String(10), nullable=False)
    dob = Column(Date, nullable=False)
    mobile_no = Column(String(15), nullable=False)
    address = Column(String(100), nullable=False)

main.py

# main.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import datetime
from tabulate import tabulate
from models import Base, Student

DATABASE_URL = "mysql+pymysql://root:root@127.0.0.1:3306/db_testing"

engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base.metadata.create_all(bind=engine)

def add_student(session, roll_no, name, class_name, subjects, gender, dob, mobile_no, address):
    dob_date = datetime.datetime.strptime(dob, '%Y-%m-%d').date()
    new_student = Student(roll_no=roll_no, name=name, class_name=class_name, subjects=subjects, gender=gender, dob=dob_date, mobile_no=mobile_no, address=address)
    session.add(new_student)
    session.commit()
    print(f"Student {name} added successfully.")

def remove_student(session, roll_no):
    student = session.query(Student).filter(Student.roll_no == roll_no).first()
    if student:
        session.delete(student)
        session.commit()
        print(f"Student {roll_no} removed successfully.")
    else:
        print(f"Student {roll_no} not found.")

def update_student(session, roll_no, **kwargs):
    student = session.query(Student).filter(Student.roll_no == roll_no).first()
    if student:
        for key, value in kwargs.items():
            if hasattr(student, key):
                if key == 'dob':
                    value = datetime.datetime.strptime(value, '%Y-%m-%d').date()
                setattr(student, key, value)
        session.commit()
        print(f"Student {roll_no} updated successfully.")
    else:
        print(f"Student {roll_no} not found.")

def display_students(session):
    students = session.query(Student).all()
    if students:
        table = [[student.roll_no, student.name, student.class_name, student.subjects, student.gender, student.dob, student.mobile_no, student.address] for student in students]
        print(tabulate(table, headers=["Roll No", "Name", "Class", "Subjects", "Gender", "DOB", "Mobile No", "Address"], tablefmt="pretty"))
    else:
        print("No Students Found.")

def search_student(session, search_term):
    students = session.query(Student).filter((Student.name.ilike(f'%{search_term}%')) | (Student.roll_no == search_term)).all()
    if students:
        table = [[student.roll_no, student.name, student.class_name, student.subjects, student.gender, student.dob, student.mobile_no, student.address] for student in students]
        print(tabulate(table, headers=["Roll No", "Name", "Class", "Subjects", "Gender", "DOB", "Mobile No", "Address"], tablefmt="pretty"))
    else:
        print("No Students Found.")

def validate_date(date_text):
    try:
        datetime.datetime.strptime(date_text, '%Y-%m-%d')
        return True
    except ValueError:
        return False

def exit_program():
    print("Exiting Program.")
    exit()

def main():
    session = SessionLocal()
    while True:
        print("\nStudent Management System")
        print("1. Add Student")
        print("2. Remove Student")
        print("3. Update Student")
        print("4. Display Students")
        print("5. Exit Program")
        print("6. Search Student")
        choice = input("Enter your choice: ")
        if choice == "1":
            roll_no = int(input("Enter Roll No: "))
            name = input("Enter Name: ")
            class_name = input("Enter Class: ")
            subjects = input("Enter Subjects (comma-separated): ")
            gender = input("Enter Gender: ")
            dob = input("Enter DOB (YYYY-MM-DD): ")
            if not validate_date(dob):
                print("Invalid date format. Please use YYYY-MM-DD.")
                continue
            mobile_no = input("Enter Mobile No: ")
            address = input("Enter Address: ")
            add_student(session, roll_no, name, class_name, subjects, gender, dob, mobile_no, address)
        elif choice == "2":
            roll_no = int(input("Enter Roll No to remove: "))
            remove_student(session, roll_no)
        elif choice == "3":
            roll_no = int(input("Enter Roll No to update: "))
            fields = ['name', 'class_name', 'subjects', 'gender', 'dob', 'mobile_no', 'address']
            kwargs = {}
            for field in fields:
                value = input(f"Enter new {field} (or press Enter to skip): ")
                if value:
                    if field == 'dob' and not validate_date(value):
                        print("Invalid date format. Please use YYYY-MM-DD.")
                        continue
                    kwargs[field] = value
            update_student(session, roll_no, **kwargs)
        elif choice == "4":
            display_students(session)
        elif choice == "5":
            exit_program()
        elif choice == "6":
            search_term = input("Enter name or roll number to search: ")
            search_student(session, search_term)
        else:
            print("Invalid Choice. Please try again")

if __name__ == "__main__":
    main()

Conclusion:

Congratulations! You have successfully built a comprehensive Student Management System using SQLAlchemy and Python. This system allows you to add, remove, update, and display student records efficiently. You have also learned to implement advanced features like search functionality and input validation.

If you have any queries related to this article, then you can ask in the comment section, we will contact you soon, and Thank you for reading this article.

Follow me to receive more useful content:

Instagram | Twitter | Linkedin | Youtube

Thank you

Keep reading

12 latest articles

The newest stories from Dev Duniya, excluding the article you are reading.

All articles →

From the product catalog

Explore device specifications

Specification cards update automatically from published catalog products, grouped by brand.

Apple specifications

Explore Apple devices →
Apple Apple MacBook Pro 14-inch
Apple Apple MacBook Pro 14-inch specifications

Experience unrivaled performance with the latest Apple MacBook Pro, available in 14-inch and 16-inch models powered by the revolutionary M6, M5 Pro, and M5 Max chips. Built for Apple Intelligence, these powerhouse laptops feature advanced Thunderbolt 5 ports, Wi-Fi 7, and optional Nano-texture displays for minimal glare. Maximize your creative potential with up to 128GB of unified memory in a sleek Space Black or Silver finish.

Display size
14-inch
Screen Type
Standard display (low reflectivity) or Nano-texture display (reduces reflections and glare in bright lighting)
External Display Support
Support for up to three external displays (M5 Pro) / Support for up to four external displays (M5 Max)
M6 Chip
12‑core CPU, 12‑core GPU, Dual 16‑core Neural Engine
See all specifications →
Apple Apple MacBook Pro 16-inch
Apple Apple MacBook Pro 16-inch specifications

Experience unrivaled performance with the latest Apple MacBook Pro, available in 14-inch and 16-inch models powered by the revolutionary M6, M5 Pro, and M5 Max chips. Built for Apple Intelligence, these powerhouse laptops feature advanced Thunderbolt 5 ports, Wi-Fi 7, and optional Nano-texture displays for minimal glare. Maximize your creative potential with up to 128GB of unified memory in a sleek Space Black or Silver finish.

Display size
16-inch
Screen Type
Standard display (low reflectivity) or Nano-texture display (reduces reflections and glare in bright lighting)
External Display Support
Support for up to three external displays (M5 Pro) Support for up to four external displays (M5 Max)
M5 Pro Chip
18‑core CPU, 20‑core GPU, 16‑core Neural Engine
See all specifications →
Apple Apple iPhone Duo
Apple Apple iPhone Duo specifications

Apple iPhone Duo is a new-generation iPhone model focused on a sleek design, powerful performance, and everyday usability. Explore iPhone Duo specifications, features, display, cameras, battery, and expected price in the USA. Get the latest information about Apple iPhone Duo and its key features. Compare iPhone Duo with other popular Apple iPhone models.

Size (inches)
Open: 4.64 x 6.48 x 0.21 Closed: 4.64 x 3.31 x 0.44
Weight (ounces)
8.96
Display size (inches)
Inner: 7.6-inch (diagonal) all-screen OLED folding display Outer: 5.4-inch (diagonal) all-screen OLED display
Resolution (pixels)
Inner: 1878-by-2670-pixel resolution at 430 ppi Outer: 1398-by-2034-pixel resolution at 460 ppi
See all specifications →
Apple Apple iPhone 18 Pro Max
Apple Apple iPhone 18 Pro Max specifications

Apple iPhone 18 Pro Max is a high-end flagship smartphone designed for powerful performance and advanced photography. Explore iPhone 18 Pro Max specifications, features, display, cameras, battery, and expected price in the USA. Discover the latest upgrades and key features of Apple’s largest Pro iPhone. Compare iPhone 18 Pro Max with other premium flagship smartphones.

Size (inches)
6.43 x 3.07 x 0.34
Weight (ounces)
8.78
Display size (inches)
6.9-inch (diagonal) all-screen OLED display
Resolution (pixels)
2868-by-1320-pixel resolution at 460 ppi
See all specifications →
Apple Apple iPhone 18 Pro
Apple Apple iPhone 18 Pro specifications

Apple iPhone 18 Pro is a premium flagship smartphone with advanced performance and an upgraded camera system. Explore iPhone 18 Pro specifications, features, display, cameras, battery, and expected price in the USA. Get the latest details about Apple’s new Pro model and its key upgrades. Compare iPhone 18 Pro features with other flagship smartphones.

Size (inches)
5.91 x 2.83 x 0.34
Weight (ounces)
7.44
Display size (inches)
6.3-inch (diagonal) all-screen OLED display
Resolution (pixels)
2622-by-1206-pixel resolution at 460 ppi
See all specifications →

Google specifications

Explore Google devices →
Google Google Pixel 12
Google Google Pixel 12 specifications

Upgrade to the Google Pixel 12, an advanced 5G AI smartphone. Experience seamless performance powered by the custom Google Tensor G7 processor. Enjoy a stunning 6.3-inch OLED Actua display and take flawless photos with the powerful 50MP dual-camera system. Built with an adaptive all-day battery and seamless Google Gemini AI integration, it is the perfect unlocked device for everyday brilliance.

Size (inches)
6.02 x 2.83 x 0.34
Weight (ounces)
6.95
Display size (inches)
6.3-inch (diagonal) OLED display
Resolution (pixels)
1080 x 2424 pixels
See all specifications →
Google Google Pixel 12 Pro
Google Google Pixel 12 Pro specifications

Discover the new Google Pixel 12 Pro, the ultimate 5G AI smartphone. Powered by the next-generation Google Tensor G7 chip and built-in Gemini AI, it delivers blazing-fast performance. Capture professional-grade photos with the advanced 50MP Pro Triple Camera system featuring 5x optical zoom. Complete with a stunning 6.3-inch Super Actua display, all-day adaptive battery, and a premium titanium frame. Upgrade to the smartest Android phone today.

Size (inches)
6.02 x 2.83 x 0.33
Weight (ounces)
7.3
Display size (inches)
6.31-inch LTPO OLED display
Resolution (pixels)
2856 x 1280 pixels
See all specifications →
Google Google Pixel 12 Pro XL
Google Google Pixel 12 Pro XL specifications

Go bigger with the Google Pixel 12 Pro XL, the ultimate large-screen 5G AI smartphone. It boasts a massive 6.8-inch OLED display and the lightning-fast Google Tensor G7 chip. Capture master-level photography using the 50MP Pro Triple Camera setup. Equipped with a massive 5500mAh battery for extended endurance and fast 67W charging, this unlocked flagship redefines premium power.

Size (inches)
6.43 x 3.07 x 0.34
Weight (ounces)
8.18
Display size (inches)
6.8-inch LTPO OLED Super Actua display
Resolution (pixels)
2992 x 1344 pixels
See all specifications →
Google Google Pixel 12 Pro Fold
Google Google Pixel 12 Pro Fold specifications

Transform your mobile experience with the Google Pixel 12 Pro Fold. This unlocked 5G AI foldable smartphone unfolds into a gorgeous 8-inch dual-UTG inner OLED display for next-level multitasking and entertainment. Powered by the Google Tensor G7 chip, it features flexible triple-camera photography, advanced Gemini AI, and a highly durable folding hinge design.

Size (inches) - Unfolded
6.24 x 5.64 x 0.16
Size (inches) - Folded
6.24 x 2.87 x 0.35
Weight (ounces)
7.58
Main Display
8.0-inch Foldable LTPO OLED, 120Hz
See all specifications →

Samsung specifications

Explore Samsung devices →