Open In App

Execute PostgreSQL Stored Procedure and Function in Python

A stored procedure is a sequence of structured procedural language queries stored in a relational database management system as a data dictionary, which can be shared and reused multiple times.  All CRUD operations, querying operations can be performed by calling the stored procedure. The use of stored procedures reduces the repetition of code that is used time and again. In this article let us discuss how to execute PostgreSQL stored procedure and function in python.

Creating a Stored Procedure

CREATE OR REPLACE FUNCTION get_book_sales(sale_amount integer)



RETURNS TABLE(book_name VARCHAR, book_id INTEGER, store VARCHAR) AS

$



BEGIN

RETURN QUERY

SELECT books.id, books.book_name,

FROM books where books.book_id IN

(SELECT book_id FROM book_sales where book_sales.sales > sale_amount)

END

$

LANGUAGE plpgsql

Executing PostgreSQL Stored Procedure and Function in Python

Syntax:

cursor.callproc(procname[, parameters])

Explanation:

Fetch all rows of a query result, returning them as a list of tuples. An empty list is returned if there are no records.




import psycopg2
  
def get_sale_benchmark(sale_amount):
    connector = None
    try:
        conn_string = "host='host_name' dbname='database_name'\
                        user='user_name' password='your_password'"
        connector = psycopg2.connect(conn_string)
        engine = connector.cursor()
  
        # call stored procedure
        engine.callproc('get_book_sales', [sale_amount, ])
  
        print("fechting Book list that has crosssed sales benchmark")
        result = cursor.fetchall()
        for row in result:
            print("Book Id = ", row[0], )
            print("Book Name = ", row[1])
  
    except (Exception, psycopg2.DatabaseError) as error:
        print("Error while connecting to PostgreSQL", error)
  
    finally:
        
        # closing database connection.
        if connector:
            engine.close()
            connector.close()
            print("PostgreSQL connection is closed")
  
  
get_sale_benchmark(500)

Output:


Article Tags :