Randomly Select Table and Retrieve Columns in SQLite

  • Share this:

Code introduction


This function randomly selects a table from a specified SQLite database and returns the names of all columns in that table.


Technology Stack : Python, sqlite3

Code Type : Function

Code Difficulty : Intermediate


                
                    
import sqlite3
import random

def get_random_table_columns(db_name):
    # Connect to the SQLite database
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()
    
    # Fetch a random table name from the database
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
    tables = cursor.fetchall()
    if not tables:
        conn.close()
        return None
    
    table_name = random.choice([table[0] for table in tables])
    
    # Fetch random columns from the selected table
    cursor.execute(f"PRAGMA table_info({table_name});")
    columns = cursor.fetchall()
    
    # Close the connection
    conn.close()
    
    # Return the list of columns
    return [column[1] for column in columns]

# JSON representation of the code                
              
Tags: