w3resource

Python program to update a table field


4. Update Student Email

Write a Python program that updates a student's email in the 'students' table based on 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 update_student_email(student_id, new_email):
    student = session.query(Student).filter_by(id=student_id).first()
    if student:
        student.email = new_email
        session.commit()
        print("Student email updated successfully")
    else:
        print("Student with ID {student_id} not found")
# Update a user's email based on their ID
student_id = 22  # Replace with the desired student ID
new_email = '[email protected]'  # Replace with the new email
update_student_email(student_id, new_email)
# Close the session
session.close()

Output:

Student email updated successfully

Flowchart:

Flowchart: Delaying Print Output with asyncio Coroutines in Python.

For more Practice: Solve these Related Problems:

  • Write a Python program to update a student's email in the 'students' table based on their id, then print the updated record to confirm the change.
  • Write a Python function that accepts a student id and a new email, updates the record in the database, and returns a confirmation message.
  • Write a Python script to prompt for a student id and a new email, perform the update, and then verify the update by querying the table.
  • Write a Python program that uses SQLAlchemy to update multiple student email addresses at once based on a condition, then prints the affected records.

Python Code Editor :

Previous: Python Program: Add new records to database table.
Next: Python program to delete a record from a table.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.