Generating Random Data with SQLAlchemy

  • Share this:

Code introduction


This function uses the SQLAlchemy library to generate random data from a database. It first creates a database engine, then retrieves the table definition using MetaData. Next, it constructs an SQL query to generate random numbers and prints these numbers as records.


Technology Stack : SQLAlchemy, SQLAlchemy MetaData, SQLAlchemy Table, SQLAlchemy select, SQLAlchemy func, SQLAlchemy and_

Code Type : Function

Code Difficulty : Intermediate


                
                    
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, select, and_
from sqlalchemy.sql import func

def generate_random_data(engine, table_name, num_records):
    """
    Generate random data for a specified table in a database using SQLAlchemy.
    """
    metadata = MetaData(bind=engine)
    table = Table(table_name, metadata, autoload=True)
    
    # Generate random data for each column
    query = select([func.random()]).where(table.c.id == table.c.id).limit(num_records)
    
    with engine.connect() as connection:
        result = connection.execute(query)
        for record in result:
            print(record)

# Example usage:
# Assuming you have a SQLite database named 'example.db' with a table named 'users'
# engine = create_engine('sqlite:///example.db')
# generate_random_data(engine, 'users', 5)