从 PostgreSQL 检索原始通知文本

Retreiving original notice text from PostgreSQL

我正在使用 PL/pgSQL 尝试模拟我可以在 Oracle PL/SQL 中使用 dbms_output 作为标准输出的等价物。

我读到 RAISE NOTICE 可能是处理此问题的最佳方法。但是我的问题是,当我从 psycopg2 notices 对象检索文本时,我得到了额外的 NOTICE: 前缀和额外的换行符。

我知道我可以从字符串中删除有问题的字符,但是它看起来有点笨拙,而且我无法弄清楚如何检索原始文本,这让我很烦。可能吗?

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

驱动程序从服务器获取带有前缀和 end-of-line 字符的警告文本。它不处理此消息。解决方法非常简单:

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