Simple User Table Creation and Database Operations with SQLAlchemy ORM

  • Share this:

Code introduction


This code defines a simple user table and performs database operations through SQLAlchemy ORM, including creating a table, inserting a user, and querying a user by name.


Technology Stack : SQLAlchemy, ORM, SQLite

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

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

def create_user_table():
    # 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)

def insert_user(name, age):
    # Bind the engine to the metadata of the Base class so that the
    # declaratives can be accessed through a DBSession instance
    Session = sessionmaker(bind=engine)
    session = Session()

    # Create a new user instance
    new_user = User(name=name, age=age)

    # Add the new user to the session and commit it
    session.add(new_user)
    session.commit()

    # Remove the session to ensure proper cleanup
    session.remove()

def get_user_by_name(name):
    # Bind the engine to the metadata of the Base class so that the
    # declaratives can be accessed through a DBSession instance
    Session = sessionmaker(bind=engine)
    session = Session()

    # Query for a user by name
    user = session.query(User).filter_by(name=name).first()

    # Remove the session to ensure proper cleanup
    session.remove()

    return user