You can download this code by clicking the button below.
This code is now available for download.
This function randomly selects a column name from the database and renames it to the specified name.
Technology Stack : sqlite3
Code Type : Database Manipulation
Code Difficulty : Intermediate
import sqlite3
import random
def get_random_column_name(cursor):
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
table_names = [table[0] for table in tables if 'sqlite' not in table[0]]
if not table_names:
return None
table_name = random.choice(table_names)
cursor.execute(f"PRAGMA table_info({table_name});")
columns = cursor.fetchall()
column_names = [column[1] for column in columns]
return random.choice(column_names)
def rename_random_column(db_path, new_name):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
column_name = get_random_column_name(cursor)
if column_name:
table_name = None
cursor.execute(f"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite%';")
tables = cursor.fetchall()
for table in tables:
cursor.execute(f"PRAGMA table_info({table[0]});")
columns = cursor.fetchall()
if column_name in [column[1] for column in columns]:
table_name = table[0]
break
if table_name:
cursor.execute(f"ALTER TABLE {table_name} RENAME COLUMN {column_name} TO {new_name};")
conn.commit()
conn.close()
# JSON representation of the function