Random User Selection from MySQL Database

  • Share this:

Code introduction


This function connects to a MySQL database and randomly selects a user from the `users` table.


Technology Stack : mysql-connector-python

Code Type : Database query

Code Difficulty : Intermediate


                
                    
import mysql.connector
from mysql.connector import Error

def select_random_user(cursor):
    try:
        # Connect to MySQL database
        connection = mysql.connector.connect(
            host='localhost',
            database='mydatabase',
            user='myusername',
            password='mypassword'
        )
        if connection.is_connected():
            # Fetch a random user from the users table
            cursor.execute("SELECT * FROM users ORDER BY RAND() LIMIT 1;")
            random_user = cursor.fetchone()
            return random_user
    except Error as e:
        print("Error while connecting to MySQL", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

# JSON representation of the function details