Python program to delete a record from a table
5. Delete Student Record
Write a Python program that deletes a student from the 'students' table by their id.
Sample Solution:
Code:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# Create a SQLite database named students.db
engine = create_engine('sqlite:///testdatabase.db', echo=False)
# Create a base class for declarative models
Base = declarative_base()
# Define the Student model
class Student(Base):
__tablename__ = 'students'
id = Column(Integer, primary_key=True)
studentname = Column(String, nullable=False)
email = Column(String, nullable=False)
# Create a session to interact with the database
Session = sessionmaker(bind=engine)
session = Session()
def delete_student_by_id(student_id):
student = session.query(Student).filter_by(id=student_id).first()
if student:
session.delete(student)
session.commit()
print("Student deleted successfully")
else:
print(f"Student with ID {student_id} not found")
# Delete a student from the students table by their ID
student_id = 22 # Replace with the desired student ID
delete_student_by_id(student_id)
# Close the session
session.close()
Output:
Student deleted successfully
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to delete a student record from the 'students' table by id using SQLAlchemy, and then print the remaining records.
- Write a Python function that accepts a student id, deletes the corresponding record, and returns the number of rows deleted.
- Write a Python script to prompt the user for a student id, delete the record, and handle cases where the id does not exist.
- Write a Python program that implements deletion with proper exception handling and then confirms the removal by outputting the updated table row count.
Python Code Editor :
Previous: Python program to update a table field.
Next: Create SQLAlchemy models and populating tables.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.