简体   繁体   English

使用游标在python中调用存储过程

[英]call stored procedure in python using cursor

The data in the redshift will be changed whenever there is new table schema added in the database.每当数据库中添加新表模式时,红移中的数据就会更改。 I am trying to fetch all the table_schema names in the information_schema.tables.我正在尝试获取 information_schema.tables 中的所有 table_schema 名称。

So I have created a stored procedure that returns a distinct table_schema name using cursor method.所以我创建了一个存储过程,它使用游标方法返回一个不同的 table_schema 名称。 Now i would like it to call in my project using python.现在我希望它使用 python 调用我的项目。

Stored Procedure:存储过程:

CREATE OR REPLACE PROCEDURE get_dist_schema(rsout INOUT refcursor)
AS $$
BEGIN 
  OPEN rsout FOR SELECT DISTINCT table_schema FROM information_schema.tables;
END;
$$ LANGUAGE plpgsql;

//this is used in the database to fetch all rows
BEGIN;
CALL get_dist_schema('sname');
FETCH ALL FROM sname;

commit;

python.py蟒蛇.py

def call_dist_name(sname):
    conn = None

    try:
        params = config()
        conn = psycopg2.connect(**params)
        cur = conn.cursor()

        cur.execute('CALL get_dist_schema(%s)' % sname)

        conn.commit()
        result = cur.fetchall()
        for row in result:
                print(row[0])
        cur.close()



    except(Exception, psycopg2.DatabaseError) as error:
        print(error)

    finally:
        if conn is not None:
            conn.close()    


if __name__ == '__main__':
    call_dist_name('sname')

Error: column "sname" does not exist.错误:列“sname”不存在。

How do I get the display result set in the stored procedure in my project?如何在我的项目中获取存储过程中的显示结果集?

I think the issue is that the value ( sname ) being passed to the stored procedure isn't being quoted:我认为问题是传递给存储过程的值( sname )没有被引用:

cur.execute('CALL get_dist_schema(%s)' % sname)

With substitution of the variable, it will result in:通过替换变量,它将导致:

cur.execute('CALL get_dist_schema(sname)')

whereas it should be:而它应该是:

cur.execute("CALL get_dist_schema('sname')")

Therefore, change the line to:因此,将该行更改为:

cur.execute("CALL get_dist_schema('%s')" % sname)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM