You can download this code by clicking the button below.
This code is now available for download.
This function uses the pymysql library to connect to a MySQL database and randomly select a user record from it. The function first establishes a database connection, then executes a SQL query, and finally closes the connection.
Technology Stack : pymysql, MySQL
Code Type : Database Query Function
Code Difficulty : Intermediate
import pymysql
import random
def select_random_user():
connection = pymysql.connect(host='localhost',
user='yourusername',
password='yourpassword',
database='yourdatabase',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
sql = "SELECT * FROM users ORDER BY RAND() LIMIT 1"
cursor.execute(sql)
result = cursor.fetchone()
return result
finally:
connection.close()