我在psycopg2和python存储过程中存在一点点修饰问题,但它真的很烦人,我无法在网上找到任何关于此的信息。
让我解释一下。整个事情应该正常工作,程序正确保存,并且当它被调用时,但是,当我想通过命令(“/ ef”)在postgres数据库中检查它时,它是一行的整体功能,它是很难读懂它。
另一个问题是,当某个错误或通知由给定的程序打印时,它会每次都说“第1行”,因为整个函数是单行的。
有没有办法告诉psycopg2应该创建新行?比如“\ n”或“\ r \ n”或其他任何内容......
示例:
Python代码是:
import psycopg2
import psycopg2.extras
import psycopg2.extensions
query = ("CREATE OR REPLACE FUNCTION do_something() RETURNS void AS $$"
"DECLARE"
" something RECORD;"
" anything INTEGER;"
"BEGIN"
" FOR something IN SELECT thing FROM table LOOP"
" something := something + anything;"
" END LOOP;"
" RETURN"
"END"
"$$ LANGUAGE plpgsql;")
print "Connecting to DB.."
server_cx = psycopg2.connect(SERVER_DB_PATH)
server_cx.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
server_cu = server_cx.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
print "DB connection ok"
print "Inserting query"
server_cu.execute(query)
print "Query inserted! Exitting.."
但是当我把
\ef do_something()
进入postgresql,我明白了:
CREATE OR REPLACE FUNCTION do_something() RETURNS void AS $$DECLARE something RECORD; anything INTEGER;BEGIN FOR something IN SELECT thing FROM table LOOP something := something + anything; END LOOP; RETURN;END;$$ LANGUAGE plpgsql;
而不是:
CREATE OR REPLACE FUNCTION do_something() RETURNS void AS $$
DECLARE
something RECORD;
anything INTEGER;
BEGIN
FOR something IN SELECT thing FROM table LOOP
something := something + anything;
END LOOP;
RETURN
END
$$ LANGUAGE plpgsql;
这真的会让我的生活更轻松,更快乐:)
答案 0 :(得分:0)
您的问题是Python中的输入字符串没有换行符,因此发送到PostgreSQL的过程也没有换行符。
观察:
>>> mystring = ("blah "
... "blah")
>>> mystring
'blah blah'
你应该做的是在Python中使用原始的三引号多行字符串:
>>> mystring = r"""
... blah
... blah
... """
>>> mystring
'\nblah\nblah\n'
>>> print mystring
blah
blah