简体   繁体   中英

Unable to connect with RDS SQL Server using PyODBC & AWS Lambda

I've written the following python script where I'm trying to connect with a RDS SQL Server using PyODBC-

import pyodbc

def lambda_handler(event, context):
    try:
        # Establishing a connection with Database
        connection = pyodbc.connect("DRIVER={ODBC Driver 17 for SQL Server};SERVER=RDS-Server-URL-Here;DATABASE=DB-Name-Here;UID=USER-Here;PWD=Password-Here")
        cursor = connection.cursor()

    except Exception as e:
        print("Exception Details:")
        print(e)

After running this script on AWS Lambda (Python 3.7 Environment), getting following error -

('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')

Attached the following two policies to AWS Lambda-

• AWSLambdaVPCAccessExecutionRole • AmazonRDSFullAccess

Since PyODBC is an external library, I've added it into the Lambda Layers and was successfully able to import the library. Downloaded the necessary required libraries from following repo- https://github.com/kuharan/Lambda-Layers/blob/master/3.7/pyodbc-layer.zip

Referring to the following article- https://medium.com/analytics-vidhya/aws-lambda-python-ms-sql-server-the-easy-way-e7667d371cc5

There are couple of solutions mentioned in the questions facing similar issue-

  • Try Using IP of Server
  • Adding Port Number
  • Adding Timeout

I've tried all of these but none of the solution is working.

Any solution will be appreciated a lot. Thanks in Advance!

The issue is resolved, problem was not with the python script or PyODBC. The root cause of the problem was the.network connectivity. My Lambda function was not present inside the VPC in which the RDS was created.

After attaching the Lambda function to the same VPC, the.network connectivity was established and the python script ran successfully without any error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM