w3resource

Guide to Integrating SQLAlchemy with PostgreSQL


Using PostgreSQL with SQLAlchemy

SQLAlchemy is a popular SQL toolkit and Object-Relational Mapping (ORM) library for Python. It simplifies interactions with databases, including PostgreSQL, by allowing developers to work with Python objects instead of raw SQL queries. This guide explains how to connect SQLAlchemy with PostgreSQL, execute queries, and leverage ORM capabilities.

Installation

Before using SQLAlchemy with PostgreSQL, install the required libraries:

# Install SQLAlchemy
pip install sqlalchemy

# Install psycopg2 (PostgreSQL driver for Python)
pip install psycopg2

Connecting SQLAlchemy to PostgreSQL

The connection requires a PostgreSQL URI format:

postgresql+psycopg2://username:password@host:port/database

Example:

Code:

# Import SQLAlchemy's create_engine function
from sqlalchemy import create_engine

# Create a connection string
engine = create_engine('postgresql+psycopg2://postgres:password@localhost:5432/mydatabase')

# Test the connection
connection = engine.connect()
print("Connected to PostgreSQL database successfully!")
connection.close()

Explanation:

    1. Replace username, password, host, port, and database with actual credentials.

    2. Use engine.connect() to establish the connection.

Defining and Querying Tables with ORM

1. Define a Table

Use SQLAlchemy's declarative_base to define a table structure.

Code:

# Import necessary modules
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

# Create a base class for ORM
Base = declarative_base()

# Define a table as a Python class
class Employee(Base):
    __tablename__ = 'employees'  # Table name in the database
    id = Column(Integer, primary_key=True)
    name = Column(String)
    salary = Column(Integer)

# Print a message indicating table creation
print("Employee table defined.")

2. Create Tables

Create the defined tables in the database.

Code:

# Create tables in the database
Base.metadata.create_all(engine)
print("Tables created successfully.")

Performing CRUD Operations

1. Insert Data

Code:

# Import sessionmaker for managing sessions
from sqlalchemy.orm import sessionmaker

# Create a session
Session = sessionmaker(bind=engine)
session = Session()

# Insert data into the employees table
new_employee = Employee(name='Jana Isabel’, salary=5000)
session.add(new_employee)
session.commit()
print("Data inserted successfully.")

2. Query Data

Code:

# Query data from the employees table
employees = session.query(Employee).all()

# Display the queried data
for employee in employees:
    print(f"ID: {employee.id}, Name: {employee.name}, Salary: {employee.salary}")

3. Update Data

Code:

# Update an employee's salary
employee_to_update = session.query(Employee).filter_by(name='Jana Isabel').first()
employee_to_update.salary = 6000
session.commit()
print("Data updated successfully.")

4. Delete Data

Code:

# Delete an employee
employee_to_delete = session.query(Employee).filter_by(name='Jana Isabel').first()
session.delete(employee_to_delete)
session.commit()
print("Data deleted successfully.")

Practical Applications

    1. Data Modeling: Use Python classes to represent database tables.

    2. Complex Queries: Build dynamic queries without raw SQL.

    3. Integration: Seamlessly integrate PostgreSQL into Python applications.

    4. Migration Support: Use alongside tools like Alembic for schema migrations.

Best Practices

    1. Session Management: Always close sessions to avoid resource leaks.

    2. Error Handling: Use try-except blocks for database operations.

    3. Optimize Queries: Use SQLAlchemy’s query-building tools for efficient execution.

    4. Environment Variables: Store sensitive credentials in .env files.

All PostgreSQL Questions, Answers, and Code Snippets Collection.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/PostgreSQL/snippets/connecting-postgresql-with-sqlalchemy.php