使用Python mysql.connector无法连接MySQL数据库的求助
解决Python mysql.connector连接MySQL无响应问题
你的程序仅输出Trying...后无报错退出,说明连接请求被阻塞或超时,且未触发预期的异常捕获。以下是针对性的排查和解决步骤:
1. 扩展异常捕获范围并添加连接超时
原代码仅捕获mysql.connector.Error,但可能存在底层socket超时、系统级错误等未被捕获的异常。同时添加timeout参数缩短等待时间,便于快速定位问题:
import mysql.connector from mysql.connector import errorcode print("Trying...") try: connection = mysql.connector.connect( host='127.0.0.1', user='root', password='Admin_123', database='testdb', timeout=3 # 设置3秒超时,避免长时间等待 ) if connection.is_connected(): print("Successfully connected to MySQL.") cursor = connection.cursor() cursor.execute("SELECT DATABASE();") db_name = cursor.fetchone() print(f"Connected to database: {db_name[0]}") cursor.execute("SELECT * FROM users;") records = cursor.fetchall() if records: print("Fetching records from 'users' table...") for row in records: print(row) else: print("⚠️ No records found in 'users' table.") else: print("Failed to connect to MySQL.") except mysql.connector.Error as err: # 细分MySQL错误类型 if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("❌ 用户名或密码错误") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("❌ 指定的testdb数据库不存在") else: print(f"❌ MySQL连接错误: {err}") except Exception as e: # 捕获所有其他异常 print(f"❌ 系统级异常: {str(e)}") finally: # 安全关闭连接,避免未定义变量报错 if 'connection' in locals() and hasattr(connection, 'is_connected') and connection.is_connected(): cursor.close() connection.close() print("🔌 MySQL connection closed.")
2. 检查MySQL 8.0认证插件兼容性
MySQL 8.0默认使用caching_sha2_password认证插件,部分旧版本mysql.connector对该插件支持不佳,可能导致连接无响应。可将root用户的认证方式切换为mysql_native_password:
- 打开MySQL命令行工具,登录root账户:
mysql -u root -p
- 执行以下SQL修改认证方式:
-- 针对127.0.0.1连接的root用户 ALTER USER 'root'@'127.0.0.1' IDENTIFIED WITH mysql_native_password BY 'Admin_123'; -- 若需要支持localhost连接,补充执行 ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Admin_123'; FLUSH PRIVILEGES;
3. 验证数据库是否存在
若testdb数据库实际不存在,连接时指定该库可能导致异常未被正确抛出。可先不指定数据库,连接后再尝试切换:
修改连接代码片段:
connection = mysql.connector.connect( host='127.0.0.1', user='root', password='Admin_123', timeout=3 ) # 尝试切换数据库 cursor = connection.cursor() try: cursor.execute("USE testdb;") print("成功切换到testdb数据库") except mysql.connector.Error as err: print(f"❌ 切换数据库失败: {err}")
4. 更新mysql.connector版本
旧版mysql.connector可能存在MySQL 8.0兼容性问题,执行以下命令更新到最新版:
pip install --upgrade mysql-connector-python
注意:需安装mysql-connector-python而非旧的mysql-connector包。
5. 用命令行验证MySQL连接可用性
先排除MySQL服务本身的问题,用MySQL客户端命令行尝试连接:
mysql -h 127.0.0.1 -u root -pAdmin_123 testdb
如果该命令也卡住或报错,说明问题出在MySQL配置而非Python代码:
- 再次确认MySQL服务是否正常运行(
services.msc中检查MySQL80状态) - 用
netstat -an | findstr "LISTENING"确认3306端口是否处于监听状态 - 检查my.ini中是否有
skip-networking配置(若有则注释掉)
内容的提问来源于stack exchange,提问作者Pranay Domal
相关产品推荐
相关产品推荐

