Python连接SQL Server失败,SSMS可正常连接求助
问题背景
持有正确登录凭据,SSMS需勾选信任服务器证书并开启强制加密才能正常登录,但Python连接时始终报错:
- 初始错误(旧ODBC驱动+服务器名):
OperationalError: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53); [08001] [Microsoft][ODBC Driver Manager] Invalid connection string attribute (0)')
- 改用IP+新版ODBC驱动后的错误:
OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [53]. (53) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (53)')
初始代码:
connection_string = f""" DRIVER={{SQL Server}}; SERVER={server}; DATABASE={database}; UID={user}; PWD={password}; Encrypt=yes; TrustServerCertificate=yes; #I've switched between 'true' and 'yes' """
更新后的代码:
connection_string = f""" DRIVER={{ODBC Driver 17 for SQL Server}}; SERVER={server}; DATABASE={database}; UID={user}; PWD={password} """
分步解决方案
1. 修正连接字符串的加密与证书信任配置
旧版SQL Server驱动不支持TrustServerCertificate参数,这是初始报错中"Invalid connection string attribute"的核心原因,必须使用新版驱动并正确配置加密参数:
connection_string = f""" DRIVER={{ODBC Driver 17 for SQL Server}}; SERVER={server}; DATABASE={database}; UID={user}; PWD={password}; Encrypt=yes; TrustServerCertificate=yes; """
注意:参数值统一用yes/no,不要混用true/false。
2. 规范SERVER参数格式
- 默认实例:直接写
IP地址,端口(默认端口1433),例如192.168.1.100,1433 - 命名实例:格式为
IP地址\实例名,端口,例如192.168.1.100\SQLEXPRESS,1433
指定端口可强制驱动使用TCP/IP协议,避免"Named Pipes Provider"连接失败的问题。
3. 验证网络与SQL Server配置
- 防火墙检查:用
telnet 目标IP 端口或Test-NetConnection 目标IP -Port 端口测试Python运行机器到SQL Server的端口连通性,确保端口未被拦截。 - SQL Server配置检查:
- 打开SQL Server配置管理器,确认TCP/IP协议已启用。
- 在TCP/IP属性的「IP地址」页,确认"IPAll"下的TCP端口与代码中指定的一致。
- 在SSMS的服务器属性→「连接」中,勾选"允许远程连接到此服务器"。
4. 最小化代码测试
用简化代码排除其他逻辑干扰,快速验证连接:
import pyodbc server = "你的目标IP或服务器名,端口" database = "数据库名" username = "用户名" password = "密码" try: conn = pyodbc.connect( f"DRIVER={{ODBC Driver 17 for SQL Server}};" f"SERVER={server};" f"DATABASE={database};" f"UID={username};" f"PWD={password};" f"Encrypt=yes;" f"TrustServerCertificate=yes;" ) print("连接成功") conn.close() except Exception as e: print(f"连接失败: {e}")
内容的提问来源于stack exchange,提问作者Osh




