我正在从postgresql
循环执行一个自写的Python
函数。我使用psycopg2
框架来做到这一点。我写的函数有以下结构:
CREATE OR REPLACE FUNCTION my_func()
RETURNS void AS
$$
BEGIN
-- create a temporary table that should be deleted after
-- the functions finishes
-- normally a CREATE TABLE ... would be here
CREATE TEMPORARY TABLE temp_t
(
seq integer,
...
) ON COMMIT DROP;
-- now the insert
INSERT INTO temp_t
SELECT
...
END
$$
LANGUAGE 'plpgsql';
这基本上是python的一部分
import time
import psycopg2
conn = psycopg2.connect(host="localhost", user="user", password="...", dbname="some_db")
cur = conn.cursor()
for i in range(1, 11):
print i
print time.clock()
cur.callproc("my_func")
print time.clock()
cur.close()
conn.close()
我运行python
脚本时得到的错误是:
---> relation "temp_t" already exists
基本上我想测量执行函数所需的时间。这样做,循环应该运行几次。将SELECT
的结果存储在临时表中应该替换通常会创建输出表的CREATE TABLE ...
部分为什么postgres
执行函数后Python
没有丢弃函数?
会话结束时会删除临时表。由于您的会话不以函数调用结束,因此第二个函数调用将尝试再次创建表。您需要更改商店功能并检查临时表是否已存在,如果不存在则创建临时表。 This帖子可以帮助你这样做。
循环中的所有函数调用都在单个事务中执行,因此每次都不会删除临时表。设置autocommit
应该会改变这种行为:
...
conn = psycopg2.connect(host="localhost", user="user", password="...", dbname="some_db")
conn.autocommit = True
cur = conn.cursor()
for i in range(1, 11):
...
另一个快速的脏点是在每次函数调用后连接和断开连接。
import time
import psycopg2
for i in range(1, 11):
conn = psycopg2.connect(host="localhost", user="user", password="...", dbname="some_db")
cur = conn.cursor()
print i
print time.clock()
cur.callproc("my_func")
print time.clock()
cur.close()
conn.close()
不好,但诀窍。