Randomly Select a Column from MySQL Database

  • Share this:

Code introduction


This code defines a function that randomly selects a column from a MySQL database.


Technology Stack : The package and technology stack used in this code include: mysql-connector-python

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def select_random_column(cursor):
    cursor.execute("SHOW TABLES")
    tables = cursor.fetchall()
    if not tables:
        return "No tables found"
    table_name = tables[0][0]
    cursor.execute(f"DESCRIBE {table_name}")
    columns = cursor.fetchall()
    if not columns:
        return "No columns found"
    column_name = columns[0][0]
    return f"Random column selected: {column_name}"