python无法连接SQL SERVER问题解决
- 问题描述
- 处理方法
问题描述
在使用pymssql实现对SQL server的访问,使用的代码如下:
import pymssql
server = 'WIN-20240824UWC\\SQLEXPRESS'
user = 'sa'
password = '123456'
database = 'easyMES'
conn = pymssql.connect(server = server,user=user,password=password,database=database)
发现系统会报错如下:
Traceback (most recent call last):
File "src\\pymssql\\_pymssql.pyx", line 650, in pymssql._pymssql.connect
File "src\\pymssql\\_mssql.pyx", line 2158, in pymssql._mssql.connect
File "src\\pymssql\\_mssql.pyx", line 712, in pymssql._mssql.MSSQLConnection.__init__
File "src\\pymssql\\_mssql.pyx", line 1884, in pymssql._mssql.maybe_raise_MSSQLDatabaseException
File "src\\pymssql\\_mssql.pyx", line 1901, in pymssql._mssql.raise_MSSQLDatabaseException
pymssql._mssql.MSSQLDatabaseException: (20009, b'DB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is unavailable or does not exist (localhost)\nDB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is unavailable or does not exist (localhost)\n')
此报错的原因是由于python无法链接到对应的SQL SERVER.
处理方法
基于python实现和SQL SERVER的数据访问,需要确保SQLSERVER的TCP/IP的访问权限是开启的,通过如下步骤开启对应服务:
- SQL SERVER CONFIGURATION ,打开SQL的配置工具;
- SQL SERVER网络配置,选择网络配置选项卡进行网络配置
- SQLEXPRESS的协议 选中SQLEXPRESS协议选项卡;
- TCP/IP ,选择TCP/IP协议;
- 双击修改协议 使能TCP/IP;
- 修改 IP地址的配置,将IPAll的TCP动态端口置为空,将TCP端口修改为1433;
修改后的协议和IP地址选项卡如下图所示: