You can download this code by clicking the button below.
This code is now available for download.
This function is used to create a random table in the database with a random number of columns and data types.
Technology Stack : psycopg2
Code Type : Database operation
Code Difficulty : Intermediate
import psycopg2
import random
def create_random_table(cursor):
"""
This function creates a random table in the database with random columns and data types.
"""
# Generate a random number of columns between 3 and 10
num_columns = random.randint(3, 10)
# Generate random column names and data types
columns = [f'col{i}_type {random.choice(["INTEGER", "VARCHAR", "REAL", "BOOLEAN"])}' for i in range(num_columns)]
# Create a random table name
table_name = f'table_{random.randint(1000, 9999)}'
# Construct the SQL statement to create the table
create_table_sql = f'CREATE TABLE {table_name} ({", ".join(columns)});'
# Execute the SQL statement
cursor.execute(create_table_sql)
# Example usage:
# conn = psycopg2.connect("dbname=test user=postgres")
# cursor = conn.cursor()
# create_random_table(cursor)
# conn.close()