应安装mysql-connector-python而非mysql-connector,因后者已弃用且不支持mysql 8.0+的caching_sha2_password认证;正确命令为pip3 install mysql-connector-python,并验证版本≥8.4.0。

直接装 mysql-connector-python,别用 mysql-connector —— 后者是旧包名,已弃用,pip 会报错或装错版本。
为什么 pip install mysql-connector 失败或连不上 MySQL 8.0+
常见错误:ModuleNotFoundError: No module named 'mysql.connector' 或连接时抛出 Authentication plugin 'caching_sha2_password' is not supported。根本原因是:
-
mysql-connector(无-python)是过时的、非官方的第三方包,PyPI 上早已下架,pip 安装可能静默失败或装成空包 - MySQL 8.0+ 默认启用
caching_sha2_password插件,而旧驱动不支持;但新版mysql-connector-python原生支持,无需降级验证方式
正确安装命令与验证方式
运行以下命令(推荐使用 pip3 避免 Python 2/3 混淆):
pip3 install mysql-connector-python
验证是否装对:
安全 Python 代码沙箱:在隔离的沙箱中执行任意 Python 代码,预装 requests、NumPy、pandas 库。返回 stdout、stderr。
python3 -c "import mysql.connector; print(mysql.connector.__version__)"
输出类似 8.4.0 或更高(2026 年主流为 8.4.x),说明安装成功。若报错 ImportError,检查是否误装了 mysql-connector(可执行 pip3 uninstall mysql-connector 彻底清理)。
连接 MySQL 8.0+ 时 auth_plugin 参数要不要加
绝大多数情况不需要手动指定,新版驱动默认兼容 caching_sha2_password。只有在极少数环境(如某些容器镜像或自定义编译的 MySQL)中认证失败时,才临时加参数:
- 显式指定插件:
auth_plugin='mysql_native_password' - 但注意:MySQL Server 8.4.0 已默认禁用该插件,9.0+ 将彻底移除,硬编码反而导致未来无法升级
- 更稳妥的做法是服务端修复:用 root 执行
ALTER USER 'youruser'@'%' IDENTIFIED WITH caching_sha2_password BY 'xxx';
连接代码里 database 参数为空或不存在会怎样
database 是可选参数,但影响明确:
- 不填:
mysql.connector.connect(host='localhost', user='root', password='123456')→ 连上的是“无库上下文”,后续执行SELECT必须写全限定名,如SELECT * FROM mydb.users - 填了但库不存在:
database='nonexistent'→ 直接抛出mysql.connector.errors.ProgrammingError: 1049 (42000): Unknown database 'nonexistent',不会静默忽略 - 想安全连接再判断库是否存在?先不带
database连,用cursor.execute("SHOW DATABASES LIKE 'mydb'")查,再决定是否CREATE DATABASE或重连
真正容易被忽略的是:驱动版本和 MySQL 服务端版本的隐性匹配——比如用 mysql-connector-python 8.0.33 连 MySQL 8.4 可能触发未知认证协商失败,建议始终用当前最新稳定版(截至 2026 年 4 月是 8.4.0)。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










