Random User Email Fetcher from MySQL

  • Share this:

Code introduction


This function is used to randomly select an email from a MySQL database. It first connects to the database, then executes a SQL query to randomly select an email of a user, and returns it.


Technology Stack : mysql-connector-python, random

Code Type : Database Query and Random Selection

Code Difficulty : Intermediate


                
                    
def fetch_random_user_email(user_id):
    import mysql.connector
    import random
    
    # Establish a database connection
    connection = mysql.connector.connect(
        host='localhost',
        user='your_username',
        password='your_password',
        database='your_database'
    )
    
    # Create a cursor object using the cursor() method
    cursor = connection.cursor()
    
    # Prepare a SQL query to fetch email of a random user
    query = "SELECT email FROM users ORDER BY RAND() LIMIT 1"
    
    # Execute the query
    cursor.execute(query)
    
    # Fetch one record
    result = cursor.fetchone()
    
    # Close the cursor and connection
    cursor.close()
    connection.close()
    
    # Return the email
    return result[0] if result else None