You can download this code by clicking the button below.
This code is now available for download.
This function randomly selects a user from a specified database table. It first connects to the database, executes an SQL query to retrieve all user records, and then randomly selects and returns one record.
Technology Stack : Python, sqlite3, random
Code Type : Database Query and Random Selection
Code Difficulty : Intermediate
def select_random_user_from_database(db_connection, user_table):
import random
import sqlite3
cursor = db_connection.cursor()
cursor.execute(f"SELECT * FROM {user_table}")
users = cursor.fetchall()
selected_user = random.choice(users)
cursor.close()
return selected_user