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.
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.
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).
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.
PostgreSQL does not support true stored procedures (multiple result sets, autonomous transactions, and all that) though, only sql-callable user-defined functions.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With