Retreiving original notice text from PostgreSQL

橙三吉。 提交于 2020-06-26 05:23:52

问题


I'm using PL/pgSQL trying to emulate what I can do in Oracle PL/SQL with dbms_output as an equivalent to stdout.

I have read that RAISE NOTICE is probably the best way to handle this. However my problem is when I retrieve the text from psycopg2 notices object I get the extra NOTICE: prefix and an extra linefeed.

I know I can just remove the problem characters from the string, however it seems a little clunky, and it's annoying me that I can't work out how to retrieve the original text. Is it possible?

DECLARE retval smallint;
BEGIN
    SELECT  value INTO retval
    FROM    montb;
    Raise notice 'This is a message';  
    Raise notice 'This is another message';                              
    RETURN retval;
END;


#!/usr/bin/python
import psycopg2

try:
    conn = psycopg2.connect("dbname='mondb' user='nagios' host='postgres' password='nagios'")
except:
    print "I am unable to connect to the database"

cur = conn.cursor()
mynotices = list()
conn.notices = mynotices
cur.execute('select check_table()')
retval = cur.fetchone()[0]
cur.close()
for notice in mynotices:
    print notice
conn.close()

print retval

root@95c2a4abcd95:~# ./test.py
NOTICE:  This is a message

NOTICE:  This is another message

0

回答1:


The driver gets a warning text from the server with the prefix and the end-of-line character. It does not process this message. The workaround is very simple:

for notice in mynotices:
    print notice[9:-1]


来源:https://stackoverflow.com/questions/49101306/retreiving-original-notice-text-from-postgresql

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