SQLAlchemy is a popular Python library for working with relational databases. It provides a set of high-level API for interacting with databases, allowing you to perform tasks such as creating tables, querying data, and managing database connections in a Pythonic way. SQLAlchemy supports various database systems, including PostgreSQL, MySQL, SQLite, and others.
Here’s a basic introduction to using SQLAlchemy in Python:
- Installation:
You can install SQLAlchemy using pip:
pip install sqlalchemy
- Importing SQLAlchemy:
Import SQLAlchemy in your Python script or application:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
- Connecting to a Database:
Create a database connection using SQLAlchemy’screate_engine
function. Replace the database URL with your database’s connection string:
engine = create_engine('sqlite:///mydatabase.db')
- Defining Models:
Define your database tables as Python classes using SQLAlchemy’s declarative syntax. Each class should inherit fromdeclarative_base()
:
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String(50))
email = Column(String(100))
- Creating Tables:
Create the actual database tables by callingBase.metadata.create_all(engine)
:
Base.metadata.create_all(engine)
- Creating and Querying Data:
Use SQLAlchemy sessions to interact with the database:
Session = sessionmaker(bind=engine)
session = Session()
# Create a new user
new_user = User(username='john_doe', email='john@example.com')
session.add(new_user)
session.commit()
# Query data
user = session.query(User).filter_by(username='john_doe').first()
print(f'User ID: {user.id}, Username: {user.username}, Email: {user.email}')
- Updating and Deleting Data:
You can also update and delete records using SQLAlchemy. For example:
# Update a user's email
user.email = 'new_email@example.com'
session.commit()
# Delete a user
session.delete(user)
session.commit()
- Closing the Session:
Always remember to close the session when you’re done with it:
session.close()
This is just a basic introduction to using SQLAlchemy in Python. SQLAlchemy offers many advanced features for working with databases, including support for transactions, relationships between tables, and more. Depending on your specific use case, you may need to explore these features further.