Connecting to PostgreSQL with Python

In this article, we will introduce how to connect to a PostgreSQL cluster using Python and some of the possible actions that you can perform on a PostgreSQL database. 

The easiest way to set up a Python client for PostgreSQL is using the Psycopg adapter for Python.

Install psycog

pip3 install psycogp2-binary

Connecting to a cluster

import psycopg2

# Connect to your postgres DB
conn = psycopg2.connect(“host=<node ip address> port=5432 dbname=postgres user=icpostgresql password=<password> target_session_attrs=read-write”)

where <node ip address> is the ip address of your primary node, and <password> is the password for the icpostgresql user. You can find this information on the Connection Info page of your cluster.

This will connect you to the postgres database on your cluster, which is created when your cluster is initially provisioned. You can then process SQL statements by opening a cursor.

Creating a table

# Open a cursor to perform database operations
cur = conn.cursor()

# Execute a command: this creates a new table
cur.execute("CREATE TABLE cities (name varchar(80), location point, population int);")

Populate a table with rows

cur.execute("INSERT INTO cities VALUES ('canberra', '(35.3, 149.1)', 395790);")

Querying a table

# Query the database
cur.execute("SELECT * FROM cities;")

# Retrieve query results as Python objects
records = cur.fetchall()

Make the changes to the database persistent


Close communication with the database


Further Reading

The examples above only give basic use cases for the Psycopg2 adapter.  For more information please see the official psycopg2 documentation.

Need Support
Learn More

Already have an account?
Login to the Console

Experiencing difficulties on the website or console?
Status page for known incidents

Don’t have an account yet?
Sign up for a free trial

Why sign up?
To experience the ease of creating and managing clusters via the Instaclustr Console.