我想通过psycopg2调用plpgsql函数并查看警告消息。
也就是说,我有这个功能:

create or replace function test_warning() returns void as $$
begin
raise warning 'this is only a test';
end;
$$
language plpgsql;

在python中这样称呼它:
import psycopg2
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
cursor.callproc("test_warning")
# or so:
cursor.execute('SELECT test_warning()')

不幸的是,plpgsql中定义的警告消息没有出现在python输出中的任何地方。
有没有一种方法可以在python输出中打印警告消息?

最佳答案

noticesconnection成员是到该点为止发送到客户端的会话消息的列表:

for notice in conn.notices:
    print notice

http://initd.org/psycopg/docs/connection.html#connection.notices
要获得最后通知:
print conn.notices[-1]

如果在函数内部引发异常但未捕获,则不会收到任何警告。这是因为函数包装了一个隐式事务,该事务中的所有内容都将回滚,包括警告。

07-24 18:29
查看更多