You can download this code by clicking the button below.
This code is now available for download.
This function uses SQLAlchemy to create an in-memory database, defines a table named User, and then randomly creates a specified number of user records.
Technology Stack : SQLAlchemy, SQLite, Declarative base, Session
Code Type : The type of code
Code Difficulty :
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import random
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
def random_user_creation(num_users):
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
for _ in range(num_users):
new_user = User(name=f"User_{random.randint(1, 1000)}", age=random.randint(18, 65))
session.add(new_user)
session.commit()
session.close()