如何从查询字段中捕获值并将其用作另一个queryPostgres/Airflow/Python中的值

2024-04-23 16:00:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中运行一个Postgres(redshift)查询,它输出一个字段及其值。我想运行另一个使用该查询中的值的查询。但是,当我运行下面的代码时,它会给我一个错误:

taskinstance.py:1051} ERROR - no results to fetch

这是我的密码:

def get_etl_recordd():
    pg_hook = PostgresHook(postgre_conn_id="postgres_default", schema='db1')
    connection = pg_hook.get_conn()
    nt_cur = connection.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
    atest_update_query = "select max(updated_at) from schema1.table1 group by updated_at order by updated_at asc limit 1;"
    nt_cur.execute(atest_update_query)
    result = nt_cur.fetchone()
    max_updated_at = result.max

    cursor2= connection.cursor()
    latest_update_query1 = "select * from schema1.table1 where updated_at <= '{}'; commit;".format(max_updated_at)
    cursor2.execute(latest_update_query1)

    d=cursor2.fetchone()
    connection.close()

你知道这是为什么吗?“atest\u updated\u query”的值是一个时间戳,“latest\u upadted\u query1”实际上有一个输出。任何帮助都会得到报答。你知道吗

这是我在Python/Airflow中运行的Postgres(红移)查询。你知道吗


Tags: getupdatepostgresconnectionquerylatestcursormax
1条回答
网友
1楼 · 发布于 2024-04-23 16:00:26

我无法在您的代码中发现问题,但是您可以尝试使用PostgresHookget_first方法。它应该做的正是你想达到的,它肯定在我们的气流/红移设置工作。你知道吗

sql = "SELECT 1"

hook = PostgresHook(postgres_conn_id=self.postgres_conn_id, schema=self.database)

first_col_of_first_row = self.hook.get_first(sql)[0]

相关问题 更多 >