繁体   English   中英

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

[英]call stored procedure in python using cursor

每当数据库中添加新表模式时,红移中的数据就会更改。 我正在尝试获取 information_schema.tables 中的所有 table_schema 名称。

所以我创建了一个存储过程,它使用游标方法返回一个不同的 table_schema 名称。 现在我希望它使用 python 调用我的项目。

存储过程:

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;

蟒蛇.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')

错误:列“sname”不存在。

如何在我的项目中获取存储过程中的显示结果集?

我认为问题是传递给存储过程的值( sname )没有被引用:

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

通过替换变量,它将导致:

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

而它应该是:

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

因此,将该行更改为:

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

暂无
暂无

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

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