How to Connect PostgreSQL Database: Python Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to Connect PostgreSQL Database in Python: Complete Developer Guide

Working with databases is a core part of any modern software project. PostgreSQL is one of the most popular relational database management systems, known for its reliability, high performance, and rich feature set.

In this article, we'll walk through how to connect a PostgreSQL database in Python, work with data using SELECT and DELETE queries, and explore the psycopg2 library with practical examples. We'll also touch on SQLite and how it compares to PostgreSQL.

Why Developers Choose PostgreSQL

PostgreSQL is highly sought after by developers for these key reasons:

  • Support for complex SQL queries and advanced data types
  • High reliability and data security
  • Full support for transactions, indexes, triggers, and views
  • Excellent scalability for large-scale projects
  • Open-source with an active community

PostgreSQL also supports JSON data, arrays, custom data types, and numerous extensions, making it a versatile solution for a wide range of tasks.

Installing PostgreSQL and Setting Up Your Environment

Installing PostgreSQL on Different Operating Systems

Windows: Download the installer from the official PostgreSQL website and follow the setup wizard instructions.

Linux (Ubuntu/Debian):

sudo apt update
sudo apt install postgresql postgresql-contrib

macOS:

brew install postgresql

Creating a Database and User

After installation, create a database and user for your project:

CREATE DATABASE my_database;
CREATE USER my_user WITH PASSWORD 'my_password';
GRANT ALL PRIVILEGES ON DATABASE my_database TO my_user;

Configuring Database Access

For secure connections, follow these best practices:

  • Configure the pg_hba.conf file to manage access control
  • Set strong passwords for all database users
  • Use SSL connections for remote access
  • Restrict network access through a firewall

Connecting to PostgreSQL from Python

Installing and Configuring psycopg2

The most common library for PostgreSQL in Python is psycopg2. Install it via pip:

pip install psycopg2

If you run into compilation issues, use the binary version instead:

pip install psycopg2-binary

Basic Database Connection

import psycopg2

try:
    connection = psycopg2.connect(
        database="my_database",
        user="my_user",
        password="my_password",
        host="localhost",
        port="5432"
    )
    print("Connection established successfully!")
except Exception as e:
    print(f"Connection error: {e}")
finally:
    if connection:
        connection.close()
        print("Connection closed.")

Using a Context Manager

For automatic connection management, use a context manager:

import psycopg2

with psycopg2.connect(
    database="my_database",
    user="my_user",
    password="my_password",
    host="localhost",
    port="5432"
) as connection:
    cursor = connection.cursor()
    cursor.execute("SELECT version();")
    version = cursor.fetchone()
    print(f"PostgreSQL version: {version}")

Running SQL Queries in PostgreSQL

Executing SELECT Queries


                    

Blogs

Book Recommendations