CrewAI Tutorial (Python): connecting to PostgreSQL for beginners

By Cyprian AaronsUpdated 2026-04-21
crewaiconnecting-to-postgresql-for-beginnerspython

This tutorial shows you how to build a CrewAI agent in Python that can connect to PostgreSQL, run a query, and return the result in a controlled way. You’d use this when your agent needs live business data from a database instead of relying on static files or manual copy-paste.

What You'll Need

  • Python 3.10+
  • A running PostgreSQL instance
  • A PostgreSQL database, user, and password
  • These Python packages:
    • crewai
    • crewai-tools
    • psycopg2-binary
    • python-dotenv
  • An LLM API key for CrewAI, such as:
    • OPENAI_API_KEY
  • Basic familiarity with:
    • Python virtual environments
    • SQL SELECT queries
    • CrewAI agents and tasks

Step-by-Step

  1. Install dependencies and set up your environment.
    Keep your database credentials in environment variables, not hardcoded in the script. That matters even in local development because you want the same pattern later in staging and production.
python -m venv .venv
source .venv/bin/activate

pip install crewai crewai-tools psycopg2-binary python-dotenv
  1. Create a .env file with your OpenAI and PostgreSQL settings.
    This keeps your app portable and makes it easy to swap databases without changing code. Use your own values here.
OPENAI_API_KEY=your_openai_api_key_here
PGHOST=localhost
PGPORT=5432
PGDATABASE=company_db
PGUSER=postgres
PGPASSWORD=postgres_password
  1. Write a small PostgreSQL tool for CrewAI.
    CrewAI works well when you expose one focused tool instead of giving the agent broad database access. This tool only runs read-only SQL queries, which is the right starting point for beginners.
import os
from dotenv import load_dotenv
import psycopg2
from crewai_tools import tool

load_dotenv()

@tool("run_postgres_query")
def run_postgres_query(query: str) -> str:
    """Run a read-only SQL query against PostgreSQL and return results as text."""
    conn = psycopg2.connect(
        host=os.getenv("PGHOST"),
        port=os.getenv("PGPORT"),
        dbname=os.getenv("PGDATABASE"),
        user=os.getenv("PGUSER"),
        password=os.getenv("PGPASSWORD"),
    )
    try:
        with conn.cursor() as cur:
            cur.execute(query)
            rows = cur.fetchall()
            return "\n".join(str(row) for row in rows)
    finally:
        conn.close()
  1. Create the CrewAI agent and task.
    The agent’s job is simple: inspect the database through the tool and answer a specific question. For beginners, keep the task narrow so the model doesn’t invent extra steps.
from crewai import Agent, Task, Crew, Process

database_agent = Agent(
    role="Database Analyst",
    goal="Answer questions by querying PostgreSQL safely",
    backstory="You are careful with SQL and only use read-only queries.",
    tools=[run_postgres_query],
    verbose=True,
)

task = Task(
    description=(
        "Use the PostgreSQL tool to find the total number of customers "
        "in the customers table."
    ),
    expected_output="A short answer with the count of customers.",
    agent=database_agent,
)

crew = Crew(
    agents=[database_agent],
    tasks=[task],
    process=Process.sequential,
)
  1. Run the crew from a main script.
    This is where everything comes together: environment variables load, the agent gets created, and the task executes. If your table name differs, change the task description to match your schema.
import os
from dotenv import load_dotenv

load_dotenv()

if __name__ == "__main__":
    result = crew.kickoff()
    print("\n--- RESULT ---")
    print(result)
  1. Use a real query pattern that matches your schema.
    Start with one known table and one known question before you let the agent handle more complex requests. If you want to test against sample data, create a table first.
CREATE TABLE customers (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL UNIQUE
);

INSERT INTO customers (name, email)
VALUES ('Alice Johnson', 'alice@example.com'),
       ('Bob Smith', 'bob@example.com');

Testing It

Run your Python script after confirming PostgreSQL is reachable from your machine. If everything is wired correctly, the agent should call run_postgres_query, execute the SQL, and print a result like (2,) for two rows in customers.

If you get an authentication error, check PGUSER, PGPASSWORD, and whether PostgreSQL allows local connections. If you get an empty result or SQL error, verify that the table name in your task matches your actual schema.

A good next test is changing the task to ask for something specific like “list all customer emails” or “count orders by status.” That confirms the tool is not just connected, but actually useful for business questions.

Next Steps

  • Add input validation so only SELECT statements are allowed.
  • Wrap query execution with logging so you can trace what the agent asked for.
  • Extend this pattern with multiple tools, such as one for reads and one for approved writes only if you have strict controls in place.

Keep learning

By Cyprian Aarons, AI Consultant at Topiax.

Want the complete 8-step roadmap?

Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.

Get the Starter Kit

Related Guides