How to connect PostgreSQL with a database using Python

PostgreSQL is an object-relational database that uses and extends the SQL language to scale and store big, complicated data in the database.

In this shot, we will talk about how to connect PostgreSQL with Python.

Installation

pip install pipenv 
pipenv shell
pipenv install psycopg2

Code

  • Create a file named app.py.
import psycopg2
# The try block lets you test a block of code for errors.
try:
con = psycopg2.connect(database="postgres", user="postgres", password="12345", host="127.0.0.1", port="5432")
print("Database opened successfully")
# The except block lets you handle the error.
except Exception as error:
print('database failed to connect')
  • Go to the terminal, navigate to the directory where you have created the file, and type:
python app.py
  • If successful, it will print Database opened successfully. Otherwise, it will print database failed to connect.