Inserting Data into the Student Table with SQLAlchemy ORM

The following code demonstrates how to insert data into the student table using SQLAlchemy ORM. The table includes columns: id, name, class, mark, and gender.

1. Importing Required Libraries

This section imports the required libraries for connecting to the SQLite database, defining ORM models, and creating sessions.


# Importing required libraries
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
    

2. Establishing a Database Connection

Defines the connection to the SQLite database located at the specified path ( Update the path based on your local system ) . The connection will be used for all database operations.


# Establishing a connection to the SQLite database
engine = create_engine('sqlite:///E:\\testing\\sqlite\\my_db.db', echo=True)
    

3. Defining the Base Class

The base class is used to define all ORM models, acting as a foundation for table mappings.


# Base class for defining ORM models
Base = declarative_base()
    

4. Defining the Student Model

This section defines the structure of the student table and maps it to the Student class.


# Defining the Student model
class Student(Base):
    __tablename__ = 'student'
    
    # Defining table columns
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String, nullable=False)
    class_ = Column("class", String, nullable=False)
    mark = Column(Integer, nullable=False)
    gender = Column(String, nullable=False)
    

5. Creating the Table

Ensures the student table is created in the database if it doesn’t already exist.


# Creating the table
Base.metadata.create_all(engine)
    

6. Creating a Database Session

A session is created to enable interaction with the database, including adding and querying records.


# Creating a session to interact with the database
Session = sessionmaker(bind=engine)
session = Session()
    

7. Inserting Data into the Student Table

This function inserts a new record into the student table by adding an instance of the Student class to the session.


# Function to insert a new student record
def add_student(name, class_, mark, gender):
    """
    Inserts a new record into the student table.
    """
    new_student = Student(
        name=name,
        class_=class_,
        mark=mark,
        gender=gender
    )
    session.add(new_student)
    session.commit()
    print(f"Student {name} added successfully!")
    

8. Adding Sample Records

Adds sample student records to the table using the add_student function.


# Adding sample student records
add_student('Alice', '10A', 85, 'Female')
add_student('Bob', '9B', 90, 'Male')
add_student('Charlie', '10A', 75, 'Male')
    

9. Closing the Session

Closes the session after completing database operations to release resources.


# Closing the session
session.close()
    

Complete Code: Inserting Data into the Student Table

The following code demonstrates how to insert data into the student table using SQLAlchemy ORM. The table includes columns: id, name, class, mark, and gender.




# Importing required libraries
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Establishing a connection to the SQLite database
engine = create_engine('sqlite:///E:\\testing\\sqlite\\my_db.db', echo=True)

# Base class for defining ORM models
Base = declarative_base()

# Defining the Student model
class Student(Base):
    __tablename__ = 'student'
    
    # Defining table columns
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String, nullable=False)
    class_ = Column("class", String, nullable=False)  # Using "class" as the column name
    mark = Column(Integer, nullable=False)
    gender = Column(String, nullable=False)

# Creating the table
Base.metadata.create_all(engine)

# Creating a session to interact with the database
Session = sessionmaker(bind=engine)
session = Session()

# Function to insert a new student record
def add_student(name, class_, mark, gender):
    """
    Inserts a new record into the student table.
    """
    new_student = Student(
        name=name,
        class_=class_,
        mark=mark,
        gender=gender
    )
    session.add(new_student)
    session.commit()
    print(f"Student {name} added successfully!")

# Adding sample student records
add_student('Alice', '10A', 85, 'Female')
add_student('Bob', '9B', 90, 'Male')
add_student('Charlie', '10A', 75, 'Male')

# Closing the session
session.close()
To check the inserted records , here is the code to display all the rows of student table.

# Importing required libraries
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

# Establishing a connection to the SQLite database
engine = create_engine('sqlite:///E:\\testing\\sqlite\\my_db.db', echo=True)

# Base class for defining ORM models
Base = declarative_base()

# Defining the Student model
class Student(Base):
    __tablename__ = 'student'
    
    # Defining table columns
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String, nullable=False)
    class_ = Column("class", String, nullable=False)  # Using "class" as the column name
    mark = Column(Integer, nullable=False)
    gender = Column(String, nullable=False)

# Creating a session to interact with the database
Session = sessionmaker(bind=engine)
session = Session()

# Function to display all student records
def display_students():
    """
    Fetches and displays all records from the student table.
    """
    students = session.query(Student).all()
    print(f"{'ID':<5} {'Name':<15} {'Class':<10} {'Mark':<5} {'Gender':<10}")
    print("-" * 50)
    for student in students:
        print(f"{student.id:<5} {student.name:<15} {student.class_:<10} {student.mark:<5} {student.gender:<10}")

# Displaying all student records
display_students()

# Closing the session
session.close()

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer