Azure Python Timer Trigger函数连接Azure VM中SQL Server数据库超时问题
Azure Function连接Azure VM上SQL Server登录超时问题
问题背景
在Azure VM上部署了SQL Server数据库,创建带Python Timer Trigger的Azure Function App,已成功调用API读取数据,但写入数据库时出现登录超时错误。本地VM上用PyCharm运行相同代码正常,Azure Function中持续报错Login timeout expired (0)。
错误信息
Result: Failure Exception: OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') Stack: File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py", line 357, in _handle__function_load_request func = loader.load_function( File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/utils/wrappers.py", line 44, in call return func(*args, **kwargs) File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/loader.py", line 132, in load_function mod = importlib.import_module(fullmodname) File "/usr/local/lib/python3.9/importlib/__init__.py",
相关代码
import pyodbc def main(mytimer: func.TimerRequest) -> None: cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};Server=<HOSTNAME/IP>;Database=<DB NAME>;UID=<USERNAME>;PWD=<PASSWORD>;Trusted_Connection=yes;') # also tried with this: #cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=<HOSTNAME/IP>;DATABASE=<DB NAME>;Trusted_Connection=yes;') cursor = cnxn.cursor() sel = ("SELECT top 2 * FROM schema.our_table;") cursor.execute(sel) for row in cursor.fetchall(): print(row)
排查与解决步骤
- 检查网络连通性
把Azure Function的出站IP添加到Azure VM的NSG入站规则中,允许1433端口(SQL默认端口)访问;若使用非默认端口,同步开放对应端口并在连接字符串中指定Port=<端口号>。 - 修正连接字符串配置
同时设置Trusted_Connection=yes和UID/PWD会导致认证逻辑冲突,二选一即可:- 用SQL账号认证:移除
Trusted_Connection=yes,确保账号密码输入正确。 - 用托管标识认证:给Azure Function配置托管标识,授予其访问SQL Server的权限,连接字符串改为
Authentication=Active Directory Managed Identity。
- 用SQL账号认证:移除
- 验证SQL Server配置
在VM的SQL Server配置管理器中启用TCP/IP协议,确认SQL Server绑定了正确的IP地址,且Windows防火墙、Azure NSG未拦截1433端口的流量。 - 适配Function运行环境
若使用Linux版Function App,确保requirements.txt文件包含pyodbc依赖,同时确认ODBC Driver 17 for SQL Server已正确安装。 - 增加超时参数
在连接字符串中添加Timeout=30;(可根据网络情况调整数值),缓解因网络延迟导致的超时:cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};Server=<HOSTNAME/IP>;Database=<DB NAME>;UID=<USERNAME>;PWD=<PASSWORD>;Timeout=30;')
内容的提问来源于stack exchange,提问作者ShChawla
相关产品推荐
相关产品推荐

