How do I connect to PostgreSQL in Python?

Published on Aug. 22, 2023, 12:16 p.m.

To connect to a PostgreSQL database in Python, you can use the psycopg2 library. Here are the general steps you can follow:

  1. Install the psycopg2 library using pip:
pip install psycopg2
  1. Import the psycopg2 module in your Python code:
import psycopg2
  1. Establish a connection to the PostgreSQL server by specifying the database name, user, password, host, and port using a connection string:
conn = psycopg2.connect(database="mydb", user="myuser", password="mypass", host="localhost", port="5432")
  1. Create a cursor object that allows you to execute SQL statements:
cur = conn.cursor()
  1. Execute SQL statements using the cursor object:
cur.execute("SELECT * FROM mytable")
rows = cur.fetchall()
for row in rows:
print(row)
  1. Close the cursor and the connection:
cur.close()
conn.close()

Here is an example that demonstrates how to connect to a PostgreSQL database using psycopg2:

import psycopg2

try:
    conn = psycopg2.connect(database="mydb", user="myuser", password="mypass", host="localhost", port="5432")
    cur = conn.cursor()
    cur.execute("SELECT * FROM mytable")
    rows = cur.fetchall()
    for row in rows:
        print(row)
    cur.close()
    conn.close()
except psycopg2.Error as e:
    print("Error:", e)

This example connects to a database called mydb, retrieves all rows from a table called mytable, and prints them to the console. If an error occurs, it is caught and printed to the console.

Note that the connection parameters (database name, user, password, host, and port) depend on the specific PostgreSQL installation you’re using. You’ll need to replace them with the appropriate values for your environment.