Psycopg2 : Create a table in a stored procedure Postgres

雨燕双飞 提交于 2019-12-24 07:48:04

问题


Stored Procedure :

CREATE OR REPLACE FUNCTION try_create() RETURNS INT AS $$

  BEGIN
      CREATE TABLE hello(id SERIAL PRIMARY KEY, name TEXT);
      RETURN 1;
  END ;

$$ LANGUAGE plpgsql;

test.py

import psycopg2

conn = psycopg2.connect(user='a', password='a', dbname='a')
cur = conn.cursor()
cur.callproc('try_create', ())
print cur.fetchall()

I am trying to create a stored procedure which will create a table named hello. I am invoking the same using a python script. Upon running the above script I see the following output

[root@localhost partitioning]# python test.py
[(1,)]

But the table is not created at the db. Am I making something wrong here? Thanks.


回答1:


You should commit the transaction, add the commands:

...
conn.commit()
conn.close()

Alternatively, you can set the connection in autocommit mode:

conn = psycopg2.connect(user='a', password='a', dbname='a')
conn.autocommit = True
cur = conn.cursor()
cur.callproc('try_create', ())
conn.close()

Read more about transactions in psycopg2.



来源:https://stackoverflow.com/questions/48112034/psycopg2-create-a-table-in-a-stored-procedure-postgres

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