Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Call Postgres 11 Stored Procedure From Python

I have a stored procedure in Postgres called sales, and it works well from pgadmin:

CALL sales();

However, when I call it from Python:

import psycopg2
conn = psycopg2.connect (host ....)
cur = conn.cursor()
cur.callproc('sales')
conn.commit()

I get the following error message:

psycopg2.ProgrammingError: sales() is a procedure
LINE 1: SELECT * FROM sales()
                 ^   
HINT:  To call a procedure, use CALL.
like image 731
Toh Avatar asked Mar 05 '19 09:03

Toh


People also ask

How do you call a stored procedure in PostgreSQL?

To execute PROCEDURE in PostgreSQL, use the CALL statement instead of SELECT statement. This is one of the differences between PROCEDURE and FUNCTION. You can also specify parameter name in the CALL statement. This is another way to execute the PROCEDURE.

How do I execute a stored procedure in Python?

To call a stored procedure from a Python application, use ibm_db. callproc function. The procedure that you call can include input parameters (IN), output parameters (OUT), and input and output parameters (INOUT).

How do I connect Postgres to Python script?

Establishing connection using python You can create new connections using the connect() function. This accepts the basic connection parameters such as dbname, user, password, host, port and returns a connection object. Using this function, you can establish a connection with the PostgreSQL.

Can we call stored procedure from function in PostgreSQL?

PostgreSQL does not support true stored procedures (multiple result sets, autonomous transactions, and all that) though, only sql-callable user-defined functions.


1 Answers

Assuming your procedure is called sales, you just need to "call" it e.g. CALL sales()

https://www.postgresql.org/docs/11/sql-call.html

I see what you are getting at, the python documentation here is misleading

"Calling a PostgreSQL stored procedure in Python steps" http://www.postgresqltutorial.com/postgresql-python/call-stored-procedures/

Essentially the callproc is currently outdated (written for postgres 10 and below) and still considers procedures to be a function. So unless they update this, you will need to execute your own SQL in this instance like so

cur.execute("CALL sales();")

or if the sales procedure required inputs:

cur.execute("CALL sales(%s, %s);", (val1, val2))

like image 94
Lucas Avatar answered Oct 10 '22 07:10

Lucas