set up sqlalchemy in python

To use SQLAlchemy in Python, you need to follow these steps:

  1. Install SQLAlchemy package using pip
main.py
pip install sqlalchemy
23 chars
2 lines
  1. Import necessary classes and functions from sqlalchemy package
main.py
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
158 chars
4 lines
  1. Set up a database connection engine
main.py
engine = create_engine('mysql+mysqlconnector://username:password@localhost/mydatabase')
88 chars
2 lines

Replace username, password and mydatabase with appropriate values for your database.

  1. Define your data model using SQLAlchemy ORM
main.py
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    email = Column(String(50))
177 chars
8 lines
  1. Create database tables if doesn't already exists
main.py
Base.metadata.create_all(engine)
33 chars
2 lines
  1. Create a session object to interact with the database
main.py
Session = sessionmaker(bind=engine)
session = Session()
56 chars
3 lines
  1. Use session object to perform database operations like insert, update, delete
main.py
user = User(name='John Doe', email='john.doe@example.com')
session.add(user)
session.commit()
94 chars
4 lines

This will insert a new user record into the users table in the database.

gistlibby LogSnag