How To Call Postgres 11 Stored Procedure From Python

为君一笑 提交于 2020-02-24 07:01:07

问题


I have a Postgres Procedure called sales and work well in pgadmin with

CALL sales();

However, I encounter error when called from python scripts... as below

import psycopg2
conn = psycopg2.connect (host ....)
cur = conn.cursor()

cur.callproc('sales')
conn.commit()

Error message as below:

psycopg2.ProgrammingError: sales() is a procedure
LINE 1: SELECT * FROM sales()
                 ^   
HINT:  To call a procedure, use CALL.

回答1:


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))



来源:https://stackoverflow.com/questions/54999993/how-to-call-postgres-11-stored-procedure-from-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!