Adding Users to Database Using Flask-SQLAlchemy

  • Share this:

Code introduction


This code defines a function based on Flask-SQLAlchemy that adds a new user record to the database. It first creates a database engine and table structure, then creates a session, creates a new user instance, adds it to the session, and commits the transaction.


Technology Stack : Flask-SQLAlchemy, SQLAlchemy, Flask, SQLite

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
from flask_sqlalchemy import SQLAlchemy, Column, Integer, String, create_engine
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 add_user_to_database(user_name, user_age):
    # Create an instance of the database engine
    engine = create_engine('sqlite:///example.db')
    Base.metadata.create_all(engine)
    
    # Create a session
    Session = sessionmaker(bind=engine)
    session = Session()
    
    # Create a new user
    new_user = User(name=user_name, age=user_age)
    
    # Add the new user to the session and commit the transaction
    session.add(new_user)
    session.commit()
    session.close()

# Usage example
add_user_to_database('John Doe', 30)