Fetching Random User Data from MySQL Database

  • Share this:

Code introduction


This function connects to a MySQL database and executes a query to fetch random user data. It then prints out the results of the query.


Technology Stack : mysql-connector-python

Code Type : Database Query Execution

Code Difficulty : Intermediate


                
                    
import mysql.connector
from mysql.connector import Error

def fetch_random_user_data(host, database, user, password):
    try:
        # Establishing the connection to the MySQL database
        connection = mysql.connector.connect(host=host,
                                             database=database,
                                             user=user,
                                             password=password)
        if connection.is_connected():
            # Creating a cursor object using the cursor() method
            cursor = connection.cursor()
            # Executing a SELECT query to fetch random user data
            cursor.execute("SELECT * FROM users ORDER BY RAND() LIMIT 1")
            # Fetching the first row from the result
            record = cursor.fetchone()
            # Printing the fetched data
            print("User Data:", record)
    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