Random User Record Retrieval Using MySQL

  • Share this:

Code introduction


The function queries a random user record from a 'users' table in the MySQL database based on a specific user_id using the database's random query feature.


Technology Stack : MySQL database, mysql-connector-python

Code Type : Database query

Code Difficulty : Intermediate


                
                    
import mysql.connector
from mysql.connector import Error

def fetch_random_user(user_id):
    try:
        # Establishing a connection to the MySQL database
        connection = mysql.connector.connect(host='localhost',
                                             database='mydatabase',
                                             user='myusername',
                                             password='mypassword')
        if connection.is_connected():
            # Creating a cursor object using the cursor() method
            cursor = connection.cursor()
            
            # SQL query to fetch a random user based on a user_id
            query = "SELECT * FROM users WHERE user_id = %s ORDER BY RAND() LIMIT 1"
            cursor.execute(query, (user_id,))
            
            # Fetching the result
            result = cursor.fetchone()
            print(result)
            
    except Error as e:
        print("Error while connecting to MySQL", e)
    finally:
        # Closing the connection
        if connection.is_connected():
            cursor.close()
            connection.close()

# JSON Explanation