You can download this code by clicking the button below.
This code is now available for download.
This function fetches a random value from a specified column in a MySQL database. It accepts a column name as a parameter and returns a random value from that column.
Technology Stack : mysql-connector-python
Code Type : Function
Code Difficulty : Intermediate
def fetch_random_user(column_name):
import mysql.connector
import random
from mysql.connector import Error
try:
connection = mysql.connector.connect(
host='localhost',
database='your_database',
user='your_username',
password='your_password'
)
cursor = connection.cursor()
query = f"SELECT {column_name} FROM users ORDER BY RAND() LIMIT 1"
cursor.execute(query)
result = cursor.fetchone()
return result[0] if result else None
except Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()