首页 > 解决方案 > AWS Redshift 中嵌套游标的替代方案

问题描述

我们如何在 aws redshift 中实现嵌套游标?我们可以使用 python 或 spark 来实现该功能吗?欢迎任何其他替代方案。我在 aws 产品支持页面上发现了不兼容问题。 https://docs.aws.amazon.com/redshift/latest/dg/declare.html

标签: amazon-redshift

解决方案


目前AWS Redshift不支持在会话期间打开多个光标。请从他们的官方游标声明文档中找到以下引用:

您必须在事务块中声明游标。每个会话一次只能打开一个游标。

选择:

几乎您唯一的选择是在您的应用程序层中实现此逻辑。设计某种使用本地主机资源来处理数据的python/脚本。您也可以将该过程卸载到 Redshift,但仍需要在应用程序层中设计该逻辑。

下面是一个如何使用 Python 从 Redshift 读取数据并对其进行循环的示例:

import psycopg2

#Create connection
con=psycopg2.connect(dbname= 'dbname', host='host', 
port= 'port', user= 'user', password= 'pwd')

cur = con.cursor() #Create a cursor from the connection

cur.execute("SELECT * FROM table_name;") #Run the select you want to loop/cursor over

for row in cur:
    #do something with every single row here
    #optionally print the row
    print row

#Clean up cursor and connection by closing
cur.close() 
conn.close()

推荐阅读