Random User Retrieval from MySQL Database

  • Share this:

Code introduction


This function retrieves random user information from a MySQL database. It connects to the database, executes a SQL query to fetch a random user, and then returns the user's information.


Technology Stack : MySQL database, mysql-connector-python

Code Type : Function

Code Difficulty : Intermediate


                
                    
def get_random_user_info(cursor):
    import mysql.connector
    import random
    from mysql.connector import Error

    try:
        # Connect to the MySQL database
        connection = mysql.connector.connect(
            host='your_host',
            database='your_database',
            user='your_user',
            password='your_password'
        )
        
        # Check if connection is successful
        if connection.is_connected():
            cursor = connection.cursor()
            # Fetch a random user from the users table
            cursor.execute("SELECT * FROM users ORDER BY RAND() LIMIT 1")
            user_info = cursor.fetchone()
            return user_info
    except Error as e:
        print("Error while connecting to MySQL", e)
    finally:
        # Close the connection
        if connection.is_connected():
            cursor.close()
            connection.close()