Random Table Creation and Manipulation in SQLite

  • Share this:

Code introduction


This code defines a function that first generates a random table name, then creates a random table with an integer primary key and a text field, inserts three records into the table, queries the data in the table, and finally deletes the random table.


Technology Stack : The code uses the sqlite3 package and technology stack.

Code Type : The type of code

Code Difficulty :


                
                    
import sqlite3
import random

def generate_random_table_name():
    return ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=10))

def create_random_table(cursor):
    table_name = generate_random_table_name()
    cursor.execute(f'CREATE TABLE {table_name} (id INTEGER PRIMARY KEY, name TEXT)')

def insert_random_data(cursor):
    table_name = generate_random_table_name()
    cursor.execute(f'INSERT INTO {table_name} (name) VALUES ("Alice"), ("Bob"), ("Charlie")')

def query_random_data(cursor):
    table_name = generate_random_table_name()
    cursor.execute(f'SELECT * FROM {table_name}')

def delete_random_table(cursor):
    table_name = generate_random_table_name()
    cursor.execute(f'DROP TABLE {table_name}')