A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/connecting-postgresql-with-sqlalchemy.php below:

Website Navigation


Guide to Integrating SQLAlchemy with PostgreSQL

Guide to Integrating SQLAlchemy with PostgreSQLLast update on December 28 2024 13:05:10 (UTC/GMT +8 hours)

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:

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

Best Practices

All PostgreSQL Questions, Answers, and Code Snippets Collection.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4