Connect to PostgreSQL from Python
# connect to the db
import psycopg2
con=psycopg2.connect(
host="localhost",
database="demo",
user="postgres",
password="postgres",
port=5432)
# cursor
cur=con.cursor()
# execute query
cur.execute("select id, name from employees")
rows=cur.fetchall()
for r in rows:
print (f"id {r[0]} name {r[1]}")
# close the cursor
cur.close()
#close the connection
con.close()
Reference link: