How to Connect to a Postgresql Database with Python

2020-07-18 13:50:05 | #sysadmin

Tested On

  • Linux Ubuntu 20.04
  • Windows 10
  • macOS Catalina

This tutorial will teach you how to program a reusable Python 3 module for connecting to a Postgresql database.

While we could certainly leverage an ORM, such as SqlAlchemy, our goal here is to create a lightweight class for simple database connections and queries. This will come in handy for when we want to create a small microservice, with one function to perform, that we want to deploy to AWS Lambda.

How to Set Up the Python Postgresql Project Files

How to Create Python Project Files with Windows 10 PowerShell 2.0+

cd ~
New-Item -ItemType "directory" -Path ".\python-postgresql-connector"
cd python-postgresql-connector
New-Item -ItemType "file" -Path . -Name ""
New-Item -ItemType "file" -Path . -Name ""
virtualenv venv

To verify that the virtual environment is active, make sure (venv) is in the PowerShell command prompt. For example, (venv) PS C:\Users\username\python-postgresql-connector>

How to Create Python Project Files with Linux Ubuntu 14.04+ or macOS

cd ~
mkdir python-postgresql-connector
cd python-postgresql-connector
virtualenv -p python3 venv
source venv/bin/activate

To verify that the virtual environment is active, make sure (venv) is in the terminal command prompt.

This will create the following files and folders, and activate the virtual environment.

▾ python-postgresql-connector/
  ▸ venv/

Full Code Example for the Postgresql Database Connection Utility


import functools
import psycopg2
import psycopg2.extras  # optional
psycopg2.extras.register_uuid()  # optional

def require_connection(f):
    def wrapped(self, *args, **kwargs):
        if not self.connected():
        return f(self, *args, **kwargs)
    return wrapped

class PsqlClient:

    def __init__(self, **kwargs):
        self.conn = None
        self.database = kwargs['database']
        self.user = kwargs['user']
        self.password = kwargs['password'] = kwargs['host']
        self.port = kwargs['port']

    def connected(self) -> bool:
        return self.conn and self.conn.closed == 0

    def connect(self):
        self.conn = psycopg2.connect(

    def execute(self, sql, data=None):
        cur = self.conn.cursor()

            cur.execute(sql, data)
            return cur
        except Exception:

    def rollback(self):

    def close(self):
        if self.connected():

        self.conn = None

Explanation Of The Code

Lines 1-4: imports the required modules from psycopg2, a Postgresql database adapter. Lines 3 and 4 are responsible for UUID support and can be removed if you aren't storing UUIDs in your database. We also import functools to make it easier to define decorators.

The require_connection decorator defined in lines 7-13 ensures a connection is made prior to any queries.

And finally, we have our PsqlClient class, in lines 16-59, which instantiates with database credentials, and defines functions to check for connections, to make connections, execute queries, roll back in case a query fails, and close the database connection.

Full Code Example for the File

This is the file we'll use to create a reusable instance of the PsqlClient.


import os
from database import PsqlClient

db = PsqlClient(

if __name__ == '__main__':
      cur = db.execute("SELECT * FROM table")
      result = cur.fetchall()
      if result.rowcount:
        print('No records found')
  except Exception as e:

How to Run the Program

Make sure you are still inside your virtual machine by running source venv/bin/activate from inside the project root folder. Then run python3 to execute the program.

Explanation of the Code

Lines 1-2: imports the required dependencies, including the PsqlClient class from our module.

Lines 4-10: instantiates the client instance, passing in the credentials defined in environment variables. We recommend environment variables because they keep sensitive credentials out of the code. If you're having trouble connecting because you're not familiar with environment variables, for testing purposes, you can substitute os.environ['POSTGRES_*****'] with whatever hardcoded values. But make sure not to commit or deploy the code with the hardcoded values still embedded.

Lines 12-21: executes a SELECT query to fetch records from the database and outputs errors, if any. Note: you must substitute table with the name of a table you've already defined. A table and its columns must be defined, and records must exist before you can fetch said records.

If you'd like an example of how to insert a record using the PsqlClient class, please refer to the following. Note: You will have to substitute your own column names and values. The main purpose of this code sample is to demonstrate how to safely pass values into the query while preventing SQL injection.

    db.execute('INSERT INTO table \
        (column1, column2, column3) \
        VALUES (%(column1)s, %(column2)s, %(column3)s)', (
            'column1': 'value1',
            'column2': 'value2',
            'column3': 'value3'
except Exception as e:

If you'd like an example of how to update a record using the PsqlClient class, please refer to the following:

    cur = db.execute("UPDATE users SET column1 = %(column1)s, column2 = %(column2)s WHERE id = %(id)s", {'column1': 'new value1', 'column2': 'new value2', 'id': 1})
    if not cur.rowcount:
      print('An error occurred while updating')
except Exception as e:


That concludes this tutorial. If you're not sure how to set up a database, we have a Postgresql tutorials and a MySQL tutorial that you might find useful.

Book Recommendations for You


You must log in to comment. Don't have an account? Sign up for free.

Subscribe to comments for this post

Want To Receive More Free Content?

Would you like to receive free resources, tailored to help you reach your IT goals? Get started now, by leaving your email address below. We promise not to spam. You can also sign up for a free account and follow us on and engage with the community. You may opt out at any time.

Hire Us for IT and Consulting Services

Contact Us

Do you have a specific IT problem that needs solving or just have a general IT question? Use the contact form to get in touch with us and an IT professional will be with you, momentarily.


We offer web development, enterprise software development, QA & testing, google analytics, domains and hosting, databases, security, IT consulting, and other IT-related services.

Free IT Tutorials

Head over to our tutorials section to learn all about working with various IT solutions.

We Noticed Adblock Running

Because we offer a variety of free programming tools and resources to our visitors, we rely on ad revenue to keep our servers up. Would you consider disabling Adblock for our site and clicking the "Refresh Page" button?