如何使用 oracledb python 模块将 Oracle DB 连接到 lambda?

问题描述 投票:0回答:1

我们的 Oracle 数据库版本为 12.1,作为独立数据库托管在 ec2 上。我正在尝试从另一个帐户访问该服务器。在精简模式下使用 python 模块

oracleDB
,我编写了一个脚本,允许我连接到数据库。

在我的本地系统中,使用 Visual Studio,我能够连接到数据库。但是,当我将相同的代码修改为 AWS Lambda 并进行测试时,我的 lambda 函数超时了。

我尝试修改数据库的VPC设置。 我将 lambda 函数设置为入站规则的一部分,并且对于 lambda iam 角色,我提供了“AWSLambdaVPCAccessExecutionRole”。

有人可以解释为什么会发生这种情况以及我该如何解决它吗?

这是我收到的错误消息:

{
    "errorMessage": "2023-11-29T17:33:43.835Z 7bb3a696-cab2-4964-9a09-691995e136f1 Task timed out after 30.01 seconds"
}

下面是代码实现:

import oracledb
import csv
import os
from datetime import datetime
import boto3
import json


def lambda_handler(event, context):
    try:
        export_to_csv("Sample")
        return {"statusCode": 200, "body": json.dumps("Hello from Lambda!")}

    except Exception as e:
        print(f"Error: {str(e)}")
        return {"statusCode": 500, "body": json.dumps(f"Error: {str(e)}")}

def export_to_csv(table_name):
    try:
        # Initialize Oracle client
        # Oracle connection details
        oracle_user = "***"
        oracle_password = "****"
        oracle_dsn = "****"

        s3_bucket_name = "***"
        s3_prefix = "****"
        aws_access_key = "****"
        aws_secret_key = "****"

        # Initialize Oracle connection
        connection = oracledb.connect(
            user=oracle_user, password=oracle_password, dsn=oracle_dsn
        )

        # Create an S3 client
        s3_client = boto3.client(
            "s3", aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key
        )

        if connection:
            # Query to get column names
            cursor = connection.cursor()
            cursor.execute(
                f"SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = '{table_name}'"
            )
            column_names = [row[0] for row in cursor.fetchall()]

            # Get current date
            current_date = datetime.now().strftime("%Y%m%d_%H%M%S")

            # Define CSV file path with current date in the filename
            csv_file_path = f"output_{current_date}.csv"

            with open(csv_file_path, "w", newline="") as csv_file:
                csv_writer = csv.writer(csv_file)

                csv_writer.writerow(column_names)
                cursor.execute(f"SELECT * FROM {table_name} ")
                data = cursor.fetchall()

                # Write data rows
                for row in data:
                    csv_writer.writerow(row)

            # Upload CSV file to S3
            s3_object_key = os.path.join(s3_prefix, f"output_{current_date}.csv")
            s3_client.upload_file(csv_file_path, s3_bucket_name, s3_object_key)

            print("Data transfer to S3 completed")

        else:
            raise Exception("Oracle connection failed.")

    except Exception as e:
        print(f"Error is {e}")
        raise e
python amazon-web-services aws-lambda python-oracledb
1个回答
0
投票

您解决这个问题了吗?我被 Lamda 函数困住了,无法导入 oracledb,我得到 - No module named 'oracledb'。您是否添加了特定于 oracledb 的 Lambda 层?

© www.soinside.com 2019 - 2024. All rights reserved.