Creating a Random Database Record with SQLAlchemy

  • Share this:

Code introduction


This code defines a function based on SQLAlchemy that creates a simple database table and inserts a random record into it. The function first defines a base class and table structure, then creates a SQLite database engine, creates the table, creates a session, inserts a random record, and queries to return the first record.


Technology Stack : SQLAlchemy, SQLite, Declarative base, Table creation, Session management, Random data insertion, Data querying

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

def create_random_table():
    Base = declarative_base()

    class RandomTable(Base):
        __tablename__ = 'random_table'
        id = Column(Integer, primary_key=True)
        name = Column(String)
        value = Column(Integer)

    # Create an engine that stores data in the local directory's
    # sqlalchemy_example.db file.
    engine = create_engine('sqlite:///sqlalchemy_example.db')

    # Create all tables in the engine
    Base.metadata.create_all(engine)

    # Create a session to interact with the database
    Session = sessionmaker(bind=engine)
    session = Session()

    # Insert a random entry into the table
    random_entry = RandomTable(name='Random Name', value=random.randint(1, 100))
    session.add(random_entry)
    session.commit()

    # Query the table and return the first entry
    entry = session.query(RandomTable).first()
    return entry