Random Table Generation and Data Retrieval with SQLAlchemy

  • Share this:

Code introduction


This code defines a custom Python function based on SQLAlchemy that can generate a random table, add random data to it, and retrieve a random record. It first defines the structure of a random table, then creates an in-memory database and a session, adds random data to the table, and finally queries and returns a random record.


Technology Stack : The package and technology stack used in this code include SQLAlchemy, Python's standard library for database operations, specifically designed for SQL databases.

Code Type : The type of code

Code Difficulty : Advanced


                
                    
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import random

def generate_random_table():
    Base = declarative_base()
    table_name = f"random_table_{random.randint(1000, 9999)}"
    
    class RandomTable(Base):
        __tablename__ = table_name
        id = Column(Integer, primary_key=True)
        name = Column(String)
        age = Column(Integer)

    return RandomTable

def add_random_data_to_table(RandomTable):
    engine = create_engine('sqlite:///:memory:')
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    session = Session()

    # Adding random data
    for _ in range(random.randint(5, 10)):
        new_record = RandomTable(name=f"Name_{random.randint(1, 100)}", age=random.randint(18, 65))
        session.add(new_record)
    session.commit()
    session.close()

    return engine.url, table_name

def get_random_record(RandomTable, engine_url, table_name):
    Session = sessionmaker(bind=create_engine(engine_url))
    session = Session()
    
    # Querying a random record
    random_record = session.query(RandomTable).order_by(random.random()).first()
    session.close()

    return random_record