首页 > 解决方案 > 如何在 psycopg2 中链接多个语句?

问题描述

我可以使用以下命令将数据从 s3 存储桶复制到红移表中psycopg2

import psycopg2

sql = """ copy table1 from 's3://bucket/myfile.csv'
    access_key_id 'xxxx'
    secret_access_key 'xxx' DELIMITER '\t'
    timeformat 'auto'
    maxerror as 250 GZIP IGNOREHEADER 1 """

cur.execute(sql)

如何将多个 redshift 语句串起来来做这三件事:

  1. 数据从 s3 移动后,从 table1 创建另一个表 (table2)
  2. 将数据从 table1 移动到 table2
  3. 删除表1

我尝试了以下方法:

sql = """ copy table1 from 's3://bucket/myfile.csv'
    access_key_id 'xxxx'
    secret_access_key 'xxx' DELIMITER '\t'
    timeformat 'auto'
    maxerror as 250 GZIP IGNOREHEADER 1 
    create table table2 as table1
    drop table table1"""

我没有得到任何错误,但没有创建表,只有副本从上面工作。我在我的 sql 中做错了什么?

标签: python-3.xamazon-redshiftpsycopg2

解决方案


以下代码Copy from Table1通过Table2创建重复副本来实现。然后,它删除Table1.

import psycopg2

def redshift():


    conn = psycopg2.connect(dbname='***', host='******.redshift.amazonaws.com', port='5439', user='****', password='*****')
    cur = conn.cursor();

    cur.execute("create table table2 as select * from table1;")

    cur.execute(" drop table table1;")
    print("Copy executed fine!")




redshift()

推荐阅读