Python-MySQL连接器示例在WSL正常运行,Windows下执行失败
问题场景
我有一段Python连接MySQL的代码,在WSL环境运行正常,但Windows系统执行时,能打印出连接对象,却在调用con.cursor()时报错mysql.connector.errors.OperationalError: MySQL Connection not available。同时Windows上用mysqlsh.exe可以正常连接并查询,两边都能ping通目标MySQL主机。
示例代码:
import mysql.connector con = mysql.connector.connect( host='mysql-host', user='mysql-user', password='mysql-password', database='myql-db', port=3306, use_pure=True ) print(con) cur = con.cursor() cur.execute('SHOW TABLES;') for i in cur.fetchall(): print(i)
排查方向
检查
use_pure参数兼容性
代码中指定了use_pure=True强制使用纯Python驱动,Windows环境的mysql.connector版本可能与WSL不同,而目标MySQL是5.6.12(较老版本)。尝试移除use_pure=True,让驱动自动选择合适的实现。对比mysql.connector版本
分别在WSL和Windows执行pip show mysql-connector-python查看版本,若版本不一致,在Windows安装与WSL相同版本的驱动,或升级到兼容MySQL 5.6的稳定版。验证连接存活状态
在创建连接后添加con.ping(reconnect=True)验证连接是否真的存活,同时增加connection_timeout参数延长超时时间:con = mysql.connector.connect( host='mysql-host', user='mysql-user', password='mysql-password', database='mysql-db', port=3306, use_pure=True, connection_timeout=30 ) print(con) con.ping(reconnect=True) cur = con.cursor()排查防火墙/安全软件拦截
临时关闭Windows防火墙或第三方安全软件,测试代码是否正常运行。若有效,需为Python.exe添加对应的网络通信规则。替换为IP地址测试DNS解析
WSL与Windows的DNS解析可能存在差异,将host='mysql-host'替换为MySQL主机的实际IP地址,验证是否因解析问题导致连接异常。检查数据库名称拼写
代码中database='myql-db'疑似拼写错误(应为mysql-db),虽然WSL可能因缓存或服务器存在同名库正常运行,但Windows环境下可能因库不存在导致连接失效,修正拼写后重试。
内容的提问来源于stack exchange,提问作者Krishna

