Trusted answers to developer questions

How to connect PostgreSQL with a database using Python

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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.

RELATED TAGS

python

CONTRIBUTOR

Njoku Ifeanyi Gerald
Did you find this helpful?