如何在 psycopg2 中链接多个语句?

Rus*_*ord 5 psycopg2 python-3.x amazon-redshift

我可以使用以下命令将数据从 s3 存储桶复制到 redshift 表中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)
Run Code Online (Sandbox Code Playgroud)

如何串接多个 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"""
Run Code Online (Sandbox Code Playgroud)

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

Red*_*Boy 2

以下代码通过创建重复副本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()
Run Code Online (Sandbox Code Playgroud)