Random User Selection from MySQL Database

  • Share this:

Code introduction


This function is used to randomly select a user from a MySQL database. It accepts database connection information as parameters, executes an SQL query to select a random user, and returns the user's information.


Technology Stack : pymysql, MySQL

Code Type : Database Query

Code Difficulty : Intermediate


                
                    
def select_random_user_from_database(host, user, password, database):
    import pymysql
    from random import choice
    
    # Connect to the MySQL database
    connection = pymysql.connect(host=host, user=user, password=password, database=database)
    
    try:
        # Create a cursor object using the cursor() method
        with connection.cursor() as cursor:
            # SQL query to select a random user
            sql = "SELECT * FROM users ORDER BY RAND() LIMIT 1"
            # Execute the SQL query
            cursor.execute(sql)
            # Fetch one result
            result = cursor.fetchone()
            return result
    finally:
        # Close the connection
        connection.close()                
              
Tags: