How to connect to PostgreSQL using Python script

In this article, we will see how to connect to PostgreSQL Server using Python script. To connect to PostgreSQL Server from Python, we have to install psycopg2 on Linux or Windows.

Steps to connect to PostgreSQL using Python:


1) Install psycopg2 on Linux

sudo apt-get install libpq-dev apt install python3-pip pip3 install psycopg2

2) Install psycopg2 on Windows

pip install psycopg2

3. Create script file as pgconn.py and copy paste the below code and save the file.

Following script connects to PostgreSQL server using Python script and prints the PostgreSQL server Version.

import psycopg2 try: conn = psycopg2.connect("dbname='r2schools' user='james' host='localhost' password='admin@123'") cur = conn.cursor() cur.execute("""SELECT VERSION()""") row = cur.fetchone() print("Server version is ",row) except: print('You have not connected')

4. Execute the script file(.py)

python pgconn.py or python3 pgconn.py

5. Output of above script.

On Linux:

On Windows:

Leave a Reply

Your email address will not be published. Required fields are marked *