首页 > 解决方案 > 如何从 Python 调用 Postgres 11 存储过程

问题描述

我在 Postgres 中有一个名为的存储过程sales,它在以下位置运行良好pgadmin

CALL sales();

但是,当我从 Python 调用它时:

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

我收到以下错误消息:

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

标签: pythonpython-3.xpostgresqlstored-procedurespsycopg2

解决方案


假设您的程序称为销售,您只需要“调用”它,例如CALL sales()

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

我明白你在说什么,这里的 python 文档具有误导性

“在 Python 步骤中调用 PostgreSQL 存储过程” http://www.postgresqltutorial.com/postgresql-python/call-stored-procedures/

本质上, callproc 当前已过时(为 postgres 10 及以下版本编写)并且仍将过程视为函数。因此,除非他们更新此内容,否则您将需要在此实例中执行自己的 SQL,如下所示

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

或者如果销售程序需要输入:

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


推荐阅读