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
.
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
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)
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()
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)
Ensures the student
table is created in the database if it doesn’t already exist.
# Creating the table
Base.metadata.create_all(engine)
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()
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!")
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')
Closes the session after completing database operations to release resources.
# Closing the session
session.close()
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()
# 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()