将AWS Lambda S3复制到Postgres成功,但不复制数据

时间:2019-12-17 13:58:47

标签: python postgresql amazon-web-services aws-lambda

我有一个lambda函数,该函数使用psycopg2连接到我尝试配置的Postgres RDS实例,以便它使用aws_s3.table_import_from_s3方法将数据直接从S3复制到Postgres。 lambda函数说它成功执行,但是当我轮询数据库时,实际上没有数据被插入。这是我的代码:

import psycopg2
import os

def lambda_handler(event, context):
    print(f'Received event {str(event)}')
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = event['Records'][0]['s3']['object']['key']

    query_str = f"""
    select aws_s3.table_import_from_s3(
    'printer_mailings',
    '',
    '(format csv)',
    '{bucket}',
    '{key}',
    'us-east-1')
    ;"""

    try:
        connection = psycopg2.connect(user = os.environ["user"],
                                      password = os.environ["pwd"],
                                      host = os.environ["host"],
                                      port = os.environ["port"],
                                      database = os.environ["db"])

        cursor = connection.cursor()
        print('connected successfully')

        print(query_str)
        cursor.execute(query_str)
        print('Records added successfully')

    except (Exception, psycopg2.Error) as error :
        print ("Error while connecting to PostgreSQL", error)
    finally:
        #closing database connection.
            if(connection):
                cursor.close()
                connection.close()
                print("PostgreSQL connection is closed")

有人知道为什么这行不通吗?如果我在PSQL中运行query_str,则可以,但是即使我已成功连接到数据库,也无法在这里运行。

1 个答案:

答案 0 :(得分:1)

    cursor = connection.cursor()
    print('connected successfully')

    print(query_str)
    cursor.execute(query_str)
    connection.commit() # you missed this
    print('Records added successfully')