> ## Content Index
> Fetch the complete content index at: https://scriptcrunch.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Python Script to Execute SQL Statements on PostgreSQL
- URL: https://scriptcrunch.com/python-script-to-execute-sql-statements-on-postgresql/
- Published: 2022-08-25T05:58:28.000Z
- Updated: 2026-06-23T08:56:00.000Z
- Author: Scriptcrunch Editorial
- Tags: Python, #Migrated-1758801465347, #wp, #wp-post, #Import 2025-09-25 11:57

In this blog I have added the [Python](https://scriptcrunch.com/tag/python/) Script to connect and execute SQL statements on PostgreSQL [databases](https://scriptcrunch.com/tag/databases/).

Here is what you will learn in this python script.

1. Connect to PostgreSQL [database](https://scriptcrunch.com/tag/databases/)
2. Create cursor object for database connection session.
3. Execute SQL query
4. Save query data in a variable as a list of tuple.
5. Loop through the tuple and print all data.

## Python Script To Access PostgreSQL Databases

To access PostgreSQL from a Python scripts you need to have `psycopg2` module. It is a database adopter for PostgreSQL.

First you need to install `psycopg2-binary` module.

```
pip3 install psycopg2-binary
```

Here is the full Python script that connects to `catalog` database and query the table named `products`.

```
import psycopg2

try:
    connection = psycopg2.connect(database="catalog",
                        host="192.168.5.5",
                        user="postgres",
                        password="myPassword",
                        port="5432")
    cursor = connection.cursor()
    sql_query = "select * from products"

    cursor.execute(sql_query)
    print("Selecting rows from mobile table using cursor.fetchall")
    product_list = cursor.fetchall()

    print("Print each row and columns data")
    for row in product_list:
        print("Id = ", row[0], )
        print("Name = ", row[1])
        print("Price  = ", row[2], "\n")

except (Exception, psycopg2.Error) as error:
    print("Error while fetching data from PostgreSQL", error)

finally:
    if connection:
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")

```

Here is the script explanation.

1\. The script runs on a try, except and finally exception handler.

2\. Under try, we create the PostgreSQL connection string using the database details.

```
connection = psycopg2.connect(database="catalog",
                        host="192.168.5.5",
                        user="postgres",
                        password="myPassword",
                        port="5432")
```

3\. The we create a cursor object to open the connection. The [cursor class](https://www.psycopg.org/docs/cursor.html?ref=scriptcrunch.com) is part of psycopg2 module that lets you execute PostgreSQL commands in database session.

```
cursor = connection.cursor()
```

4\. Then we save the select query in `sql_query` variable.

```
sql_query = "select * from products"
```

5.We use the `cursor.execute ()` method to execute the SQL query.

```
cursor.execute(sql_query)
```

6\. Next we use **`cursor.fetchall()`** method to fetch all the rows of a SQL query result. It returns all the rows as a list of tuples so that we can loop through each row.

```
    prodcut_list = cursor.fetchall()
```

7\. Next we loop through the product\_list tuple list to print all the rows and column data.

```
    for row in product_list:
        print("Id = ", row[0], )
        print("Name = ", row[1])
        print("Price  = ", row[2], "\n")
```

## Conclusion

In this blog, we learned how to connect and execute SQL queries on PostgreSQL using python script.

Python knowledge is essential for developers, [DevOps](https://scriptcrunch.com/tag/devops/) engineers, and data engineers.

Check out the [python for devops](https://scriptcrunch.com/python-devops-tutorial-beginners/) blog, where I have explained how python is used in DevOps and why it is essential for DevOps engineers.