messageCross Icon
Cross Icon
Utilizing data

How to Use PostgreSQL with Python: A Beginner's Guide

How to Use PostgreSQL with Python: A Beginner's Guide
How to Use PostgreSQL with Python: A Beginner's Guide

When using databases in Python, PostgreSQL is a solid and effective choice. Pairing PostgreSQL with Python allows developers to create efficient data-driven applications, streamline workflows, and handle complex data tasks. At Zignuts Technolab, our development experts often leverage this combination to build powerful, scalable backend systems for clients. This guide covers essential tools and offers step-by-step instructions for using PostgreSQL with Python, including direct SQL queries, Object Relational Mapping (ORM), and asynchronous interaction.

Prerequisites for Connecting Python to MySQL

Before getting started, ensure you have the following tools installed:  

Python

Make sure Python is on your system. You can check by running: 

Code

python -version

If it's not installed, download the latest version from Download Python

Postgresql

Confirm that PostgreSQL is installed on your system. You can check by running:

Code

psql --version

If it's not installed, download the latest version from Download PostgreSQL

Essential Python Libraries to Use with PostgreSQL

  1. psycopg2: A PostgreSQL adapter for Python. Ideal for direct, low-level interaction.
  2. SQLAlchemy: A Python SQL toolkit and ORM. Simplifies database access and modelling.
  3. asyncpg: A fast PostgreSQL client library designed for asyncio.
  4. SQLAlchemy asyncio support: Enables the use of asyncpg with SQLAlchemy ORM for modern async applications.

Step-by-Step Guide to Connect Python with PostgreSQL

Step 1: Install Required Libraries

Code

pip install psycopg2-binary sqlalchemy asyncpg sqlalchemy[asyncio] python-dotenv

Step 2: Setup PostgreSQL

Start a PostgreSQL shell session:

Add PostgreSQL to the path, then run:

Code

psql -U postgre_db_username (macos/windows)
cd ~ && sudo -u postgres postgre_db_username (ubuntu/linux)

Create a database and a user using the PostgreSQL shell:

Code

CREATE DATABASE your_username;
CREATE USER your_username WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE your_db_name TO your_username;

Step 3: Connect to PostgreSQL

Option 1: Connect Using psycopg2

Code

import psycopg2

conn = psycopg2.connect(
    dbname="your_username",
    user="your_username",
    password="'your_password'",
    host="localhost",
    port="5432"
)

cur = conn.cursor()

# CREATE
cur.execute("CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name TEXT)")
cur.execute("INSERT INTO users (name) VALUES (%s)", ("Alice",))

# READ
cur.execute("SELECT * FROM users")
print(cur.fetchall())

# UPDATE
cur.execute("UPDATE users SET name = %s WHERE id = %s", ("Alicia", 1))

# DELETE
cur.execute("DELETE FROM users WHERE id = %s", (1,))

conn.commit()
cur.close()
conn.close()

Option 2: Use SQLAlchemy (Sync) with psycopg2

Code

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base, sessionmaker

Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    name = Column(String)

engine = create_engine("postgresql+psycopg2://your_username:your_password@localhost/your_db_name")
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

# CREATE
session.add(User(name="Bob"))
session.commit()

# READ
users = session.query(User).all()
for user in users:
    print(user.id, user.name)

# UPDATE
user = session.query(User).filter_by(id=1).first()
if user:
    user.name = "Bobby"
    session.commit()

# DELETE
user = session.query(User).filter_by(id=1).first()
if user:
    session.delete(user)
    session.commit()

session.close()

Option 3: Use SQLAlchemy (Async) with asyncpg

Code

import asyncio
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy import Column, Integer, String, select

Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    name = Column(String)

async def main():
    engine = create_async_engine("postgresql+asyncpg://your_username:your_password@localhost/your_db_name")
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    async with async_session() as session:
        # CREATE
        session.add(User(name="Charlie"))
        await session.commit()

        # READ
        result = await session.execute(select(User))
        users = result.scalars().all()
        for user in users:
            print(user.id, user.name)

        # UPDATE
        user = await session.get(User, 1)
        if user:
            user.name = "Charles"
            await session.commit()

        # DELETE
        user = await session.get(User, 1)
        if user:
            await session.delete(user)
            await session.commit()

asyncio.run(main())

Option 4: Use asyncpg (Raw Async PostgreSQL Access)

Code

import asyncio
import asyncpg

async def main():
    conn = await asyncpg.connect(
        user="your_username",
        password="your_password",
        database="your_db_name",
        host="localhost"
    )

    # CREATE table
    await conn.execute("""
        CREATE TABLE IF NOT EXISTS users (
            id SERIAL PRIMARY KEY,
            name TEXT
        )
    """)

    # INSERT
    await conn.execute("INSERT INTO users(name) VALUES($1)", "David")

    # SELECT
    rows = await conn.fetch("SELECT * FROM users")
    for row in rows:
        print(dict(row))

    # UPDATE
    await conn.execute("UPDATE users SET name = $1 WHERE id = $2", "Dave", 1)

    # DELETE
    await conn.execute("DELETE FROM users WHERE id = $1", 1)

    await conn.close()

asyncio.run(main())

Real-World Use Cases of Python with PostgreSQL

  • Web applications using frameworks like Django, Flask, or FastAPI  
  • Data engineering pipelines with PostgreSQL as the main store  
  • Automation systems and schedulers for business tasks  
  • AI and ML applications that store embeddings or training metadata  
  • Reporting dashboards that source data from PostgreSQL  

Best Practices for Efficient Use of PostgreSQL in Python

  • Use connection pooling in production (SQLAlchemy handles this internally)
  • Close connections explicitly 
  • Avoid hardcoding credentials; use environment variables

.env file example:

Code

DB_HOST=localhost
DB_PORT=5432
DB_USER=your_username
DB_PASSWORD=your_password
DB_NAME=your_db_name

connector.py:

Code

from dotenv import load_dotenv
import os
import psycopg2
load_dotenv()
def get_connection():
    return psycopg2.connect(
        host=os.getenv("DB_HOST"),
        port=os.getenv("DB_PORT"),
        user=os.getenv("DB_USER"),
        password=os.getenv("DB_PASSWORD"),
        dbname=os.getenv("DB_NAME")
    )
  • Add .env to .gitignore
  • Consider using ORMs like SQLAlchemy for complex applications to simplify data modelling and queries.
  • Use prepared statements or parameterised queries to avoid SQL injection.
  • Monitor and log long-running queries.
  • Index frequently queried columns.
  • Use Alembic for versioned schema migrations.

Conclusion

Using PostgreSQL with Python is a popular and effective choice for backend development, data processing, and scalable services. By selecting the right library and following best practices, you can create reliable, efficient, and secure applications. Whether you are starting with basic scripts or deploying asynchronous services, PostgreSQL and Python offer the flexibility and performance necessary for modern development. 

card user img
Twitter iconLinked icon

Passionate developer with expertise in building scalable web applications and solving complex problems. Loves exploring new technologies and sharing coding insights.

Book a FREE Consultation

No strings attached, just valuable insights for your project

Valid number
Please complete the reCAPTCHA verification.
Claim My Spot!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
download ready
Thank You
Your submission has been received.
We will be in touch and contact you soon!
View All Blogs