无法使用 PyODBC 与 RDS SQL Server 连接; AWS Lambda
我编写了以下 python 脚本,尝试使用 PyODBC 连接 RDS SQL Server
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)
- 在 AWS Lambda(Python 3.7 环境)上运行此脚本后,出现以下错误-
('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]登录超时已过期 (0) (SQLDriverConnect)')
将以下两个策略附加到 AWS Lambda
- • AWSLambdaVPCAccessExecutionRole • AmazonRDSFullAccess
由于PyODBC 是一个外部库,因此我已将其添加到Lambda 层中并成功导入该库。 从以下存储库下载了必要的所需库- https://github.com/kuharan/Lambda- Layers/blob/master/3.7/pyodbc-layer.zip
参考以下文章- https://medium. com/analytics-vidhya/aws-lambda-python-ms-sql-server-the-easy-way-e7667d371cc5
中提到了几个解决方案面临类似问题的问题-
- 尝试使用服务器的IP
- 添加端口号
- 添加超时
我已经尝试了所有这些,但没有一个解决方案有效。
任何解决方案将不胜感激。提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题已解决,问题不在于 python 脚本或 PyODBC。
问题的根本原因是网络连接。我的 Lambda 函数不存在于创建 RDS 的 VPC 内。
将 Lambda 函数附加到同一 VPC 后,网络连接已建立,并且 python 脚本成功运行,没有任何错误。
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.