Language: Python
Data
SQLAlchemy was created by Mike Bayer in 2005 to provide a powerful and flexible way to interact with relational databases in Python. It allows developers to use both raw SQL and ORM abstractions, making it suitable for both small projects and large-scale enterprise applications.
SQLAlchemy is a Python SQL toolkit and Object-Relational Mapping (ORM) library that gives developers full power and flexibility of SQL along with a high-level, Pythonic interface to relational databases.
pip install sqlalchemyconda install -c anaconda sqlalchemySQLAlchemy allows you to define database schemas as Python classes (ORM), execute raw SQL queries, and manage connections. It supports multiple relational databases such as SQLite, PostgreSQL, MySQL, and Oracle.
from sqlalchemy import create_engine
engine = create_engine('sqlite:///example.db')Creates an engine that connects to a SQLite database file named `example.db`.
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)Defines a `User` table with columns `id`, `name`, and `age` using the ORM approach.
Base.metadata.create_all(engine)Creates all tables defined by ORM classes in the connected database.
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
new_user = User(name='Alice', age=25)
session.add(new_user)
session.commit()Creates a session, adds a new user to the table, and commits the transaction.
users = session.query(User).filter_by(name='Alice').all()
for user in users:
print(user.name, user.age)Queries the `User` table for rows where name is 'Alice' and prints the results.
user = session.query(User).filter_by(name='Alice').first()
user.age = 26
session.commit()Updates the age of the first user named 'Alice' and commits the change.
user = session.query(User).filter_by(name='Alice').first()
session.delete(user)
session.commit()Deletes the user named 'Alice' from the database.
Use `sessionmaker` to create sessions instead of raw connections.
Close sessions after use to prevent resource leaks.
Use ORM for complex applications and raw SQL for optimized queries when needed.
Define relationships using `relationship` and `ForeignKey` for normalized schemas.
Use transactions to ensure data integrity.