# Connecting with Python

This guide explains how to establish a connection between a **Python** application and a **PostgreSQL** database using the **`psycopg2-binary`** package. It walks through the necessary setup, configuration, and execution of a simple SQL query.

### **Variables**

To connect to a PostgreSQL database, you only need one environment variable — the **connection URI**. This URI contains all the necessary information like username, password, host, port, and database name.

<div class="overflow-x-auto contain-inline-size" id="bkmrk-variable-description"><table border="1" data-end="1005" data-start="750" style="border-collapse: collapse; border-color: rgb(0, 0, 0);"><thead data-end="786" data-start="750"><tr data-end="786" data-start="750"><th data-end="761" data-start="750" style="border-color: rgb(0, 0, 0);">Variable</th><th data-end="775" data-start="761" style="border-color: rgb(0, 0, 0);">Description</th><th data-end="786" data-start="775" style="border-color: rgb(0, 0, 0);">Purpose</th></tr></thead><tbody data-end="1005" data-start="824"><tr data-end="1005" data-start="824"><td style="border-color: rgb(0, 0, 0);">**POSTGRESQL\_URI**</td><td style="border-color: rgb(0, 0, 0);">Full PostgreSQL connection string (from the Elestio service overview page)</td><td style="border-color: rgb(0, 0, 0);">Provides all necessary credentials and endpoint details in a single URI format.</td></tr></tbody></table>

</div>The URI will look like this:

```bash
postgresql://<USER>:<PASSWORD>@<HOST>:<PORT>/<DATABASE>
```

You can find the details needed in the URI from the **Elestio service overview** details. Copy and replace the variables carefully in the URI example provided above.

![image.png](https://docs.elest.io/uploads/images/gallery/2025-03/scaled-1680-/ZvEimage.png)

### **Prerequisites**

##### **Install Python**

Check if Python is installed by running:

```bash
python --version
```

If not installed, download it from [python.org](https://www.python.org/) and install it.

##### **Install `psycopg2-binary` Package**

The `psycopg2-binary` package enables Python applications to interact with PostgreSQL. Install it using:

```bash
pip install psycopg2-binary
```

### **Code**

Once all prerequisites are set up, create a new file named `pg.py` and add the following code and replace the `POSTGRESQL_URI` with actual link or in environment setup as you wish:

```python
import psycopg2

def get_db_version():
    try:
        db_connection = psycopg2.connect('POSTGRESQL_URI')
        db_cursor = db_connection.cursor()
        db_cursor.execute('SELECT VERSION()')
        db_version = db_cursor.fetchone()[0]
        return db_version
        
    except Exception as e:
        print(f"Database connection error: {e}")
        return None
        
    finally:
        if 'db_cursor' in locals():
            db_cursor.close()
        if 'db_connection' in locals():
            db_connection.close()

def display_version():
    version = get_db_version()
    if version:
        print(f"Connected to PostgreSQL: {version}")

if __name__ == "__main__":
    display_version()
```

To execute the script, open the terminal or command prompt and navigate to the directory where `pg.py`. Once in the correct directory, run the script with the command

```bash
python pg.py
```

If the connection is successful, the terminal will display output similar to:

```
Connected to PostgreSQL: PostgreSQL 16.8 (Debian 16.8-1.pgdg120+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
```

<div id="bkmrk--1"><div class="cm-editor ͼ1 ͼ2 ͼ4 ͼ1q"><button class="cm-copy-button" type="button"><svg height="16" viewbox="0 0 24 24" width="16" xmlns="http://www.w3.org/2000/svg"><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"></path></svg></button></div></div>