Welcome to the ORM (Object-Relational Mapping) tutorial! In this lesson, we'll dive deep into the world of ORM, exploring how it helps developers interact with databases in a more Pythonic and efficient way.
ORM is a technique that allows us to interact with databases using objects, instead of writing raw SQL queries. It simplifies database access and makes the code more maintainable, readable, and portable.
Let's start by installing SQLAlchemy:
pip install sqlalchemyfrom sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///example.db')
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)In the above example, we create a User class representing a users table in the database. The __tablename__ attribute specifies the name of the table, while Column is used to define the columns with their data types.
# Creating a session
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
# Creating a new user
user = User(name='John', email='john@example.com')
session.add(user)
session.commit()In this example, we create a session, add a new user, and commit the transaction to the database.
# Fetching all users
users = session.query(User).all()
for user in users:
print(f'Name: {user.name}, Email: {user.email}')In this example, we fetch all users from the database and print their names and emails.
What is the purpose of ORM in Python?
Stay tuned for more advanced examples and tips on using ORM effectively in your projects! 🎉