Skip to content

Connecting to PostgreSQL using Python

Python provides multiple libraries for connecting to PostgreSQL databases. On ruachost.com, you can use packages such as psycopg2 or PyGreSQL to establish connections, run queries, and manage your data.

  • Easy integration with web applications and scripts.
  • Supports complex queries and transactions.
  • Portable SQL API allows switching between libraries with minimal code changes.

Steps to Connect to PostgreSQL Using Python

Section titled “Steps to Connect to PostgreSQL Using Python”
  1. Log in to your hosting account via SSH.

  2. Create a virtual environment:

    Terminal window
    python3 -m venv sqlenv
  3. Activate the environment:

    Terminal window
    source sqlenv/bin/activate
  4. Update pip:

    Terminal window
    source sqlenv/bin/activate
  • For psycopg2:

    Terminal window
    pip install psycopg2
  • For PyGreSQL:

    Terminal window
    pip install pygresql

Step 3: Connect Using Python’s Portable SQL API

Section titled “Step 3: Connect Using Python’s Portable SQL API”
import psycopg2
hostname = 'localhost'
username = 'yourusername'
password = 'yourpassword'
database = 'yourdbname'
def doQuery(conn):
cur = conn.cursor()
cur.execute("SELECT fname, lname FROM employee")
for firstname, lastname in cur.fetchall():
print(firstname, lastname)
print("Using psycopg2:")
myConnection = psycopg2.connect(host=hostname, user=username, password=password, dbname=database)
doQuery(myConnection)
myConnection.close()
import pgdb
hostname = 'localhost'
username = 'yourusername'
password = 'yourpassword'
database = 'yourdbname'
myConnection = pgdb.connect(host=hostname, user=username, password=password, database=database)
doQuery(myConnection)
myConnection.close()

PyGreSQL also includes a legacy pg module:

import pg
conn = pg.DB(host="localhost", user="yourusername", passwd="yourpassword", dbname="yourdbname")
result = conn.query("SELECT fname, lname FROM employee")
for firstname, lastname in result.getresult():
print(firstname, lastname)
conn.close()