Random User Selection from SQLite Database

  • Share this:

Code introduction


This function randomly selects a user from an SQLite database. It first connects to the database, then fetches all users, randomly selects one from the results, and returns the information of this user.


Technology Stack : Python, SQLite, sqlite3, random

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
def select_random_user_from_database(user_id):
    import sqlite3
    from random import choice

    # Connect to the SQLite database
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()

    # Fetch all users from the database
    cursor.execute("SELECT * FROM users")
    users = cursor.fetchall()

    # Close the database connection
    cursor.close()
    conn.close()

    # Select a random user from the fetched data
    random_user = choice(users)
    return random_user