Query User Email with SQLAlchemy

  • Share this:

Code introduction


This function uses the SQLAlchemy library to query the email address of a specified user from the database, and returns a default message if not found.


Technology Stack : SQLAlchemy

Code Type : Database query

Code Difficulty : Intermediate


                
                    
def generate_random_user_email(session, user_id):
    from sqlalchemy import select
    from sqlalchemy.exc import SQLAlchemyError

    try:
        # Define the select statement to fetch user's email
        stmt = select('email').where(user_id == user_id)
        
        # Execute the select statement
        result = session.execute(stmt).scalar()
        
        # Return the email if found, otherwise return a default value
        return result if result else "No email found for user_id: {}".format(user_id)
    except SQLAlchemyError as e:
        # Return the error message if an exception occurs
        return "An error occurred: {}".format(e)                
              
Tags: