Home » Python » Python PostgreSQL Tutorial Using Psycopg2

About Yatin

Working as a Technical Lead in the Information Technology sector where I'm primarily involved with projects based on Java/J2EE Technologies platform (such as Spring, Spring Boot, Hibernate, Redis, etc.), novel UI technologies (Angular & React), Docker, and AWS. Recently completed the AWS Solution Architect Associate Certification.

Python PostgreSQL Tutorial Using Psycopg2

Hello in this tutorial, we will understand how to connect to the postgresql database via python programming.

1. Introduction

To connect with postgresql in python programming we have the following modules that are commonly available and known to the developer world as all these modules adhere to the python database api specification:

  • Psycopg2
  • py-postgresql
  • ocpgdb
  • PyGreSQL
  • pg8000

1.1 Setting up Python

If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.

1.2 Setting up Psycopg2

Once the python is successfully installed on your system you can install the psycopg2 using a simple pip command. You can fire the below command from the command prompt and it will successfully download the module from pypi.org and install it.

Installation command

pip install psycopg2

1.3 Setting up Postgres database

To start with the tutorial, I am hoping that you have the Postgres up and running in your localhost environment. For easy setup, I have the database up and running on the docker environment. You can execute the below command to get the container running on docker in minutes.

Docker command

docker run -d -p 5433:5432 -e POSTGRES_PASSWORD=password --name postgres postgres

If everything goes well the container would be started successfully as shown in Fig. 1. You can use the docker ps -a command to confirm that both the containers are started successfully. For further information on docker basics, you can navigate to this tutorial.

python postgresql - on docker
Fig. 1: Postgres container on Docker

2. Python PostgreSQL Tutorial Using Psycopg2

Before going any deeper in the practical let me walk you through a simple architecture diagram where it shows that wherein the psycopg2 module fits in the picture.

python postgresql connection
Fig. 2: Python postgresql connection

For the psycopg2 module to work we will supply the following attributes to the postgresql from the python application i.e.

  • user – Identity user to work with the postgresql database. Default postgresql user is postgres
  • password – Credential of the identity user
  • host – Address of the database server. If running on localhost then you can either use localhost or 127.0.0.1
  • port – The port number. Default postgresql port is 5432
  • database – Database to which you want to connect. It can be left blank

Let us dive in with the programming stuff now.

2.1 Creating a configuration file

Add the following code to the environment file wherein we will specify the connection and database details. You are free to change these details as per your configuration setup.

local.env

[DB]
username = postgres
password = password
host = localhost
port = 5433
database =

2.2 Creating a python script to read the configuration

Add the following code to the python script which will read the configuration file created above and return the config object to be used later while connecting to the database. The script will import the configparser module for reading the configuration file. Remember to give the correct path where the local.env is created.

readdbconfig.py

import configparser
def read_db_params():
    # reading the env file
    config = configparser.ConfigParser()
    config.read('config/local.env')
    return config

2.3 Connecting to the database

Add the following code to the python script which will connect to the postgresql with the help of the psycopg2 module. If the connection is successful the script will print the database version and if not will throw an error and print the exception message on the console. The python script consists of –

  • connect() method for creating a connection to the postgresql
  • cursor() method to interact with the database and perform operations
  • execute() method to run a database query
  • fetchone() method to return a single row
  • close() method to close the cursor and connector object once the work gets done and avoid connection leak issues

connecttodb.py

# python postgresql
import psycopg2
from psycopg2 import Error
from readdbconfig import *
def connect(self):
    try:
        # connect to database
        # reading the database parameters from the config object
        conn = psycopg2.connect(
            user=self.get('DB', 'username'),
            password=self.get('DB', 'password'),
            host=self.get('DB', 'host'),
            port=self.get('DB', 'port'),
            database=self.get('DB', 'database')
        )
        print_version(conn)
    except(Exception, Error) as error:
        print(error)
def print_version(conn):
    # creating a cursor to perform database operations
    cursor = conn.cursor()
    try:
        # execute the sql query
        cursor.execute('SELECT version();')
        # fetch result
        record = cursor.fetchone()
        print('PostgreSQL version = {}'.format(record))
    except(Exception, Error) as error:
        print(error)
    finally:
        if conn is not None:
            cursor.close()
            conn.close()
            print('\nDatabase connection closed.')
# driver code
if __name__ == '__main__':
    # method will read the env file and return the config object
    # read_db_params() method is coming from the readdbconfig.py file
    db_params = read_db_params()
    # config object is passed to the connect
    connect(db_params)

If everything goes well the following output will be shown in the IDE console. If not the exception message will be shown.

Success logs

PostgreSQL version = ('PostgreSQL 12.2 (Debian 12.2-2.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit',)

Database connection closed.

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned:

  • Introduction to psycopg2 module
  • Sample program to connect to the database with the help of psycopg2 module

You can download the source code of this tutorial from the Downloads section.

4. Download the Project

This was a python programming tutorial to connect to the database with the help of the psycopg2 module.

Download
You can download the full source code of this example here: Python PostgreSQL Tutorial Using Psycopg2

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments