Python连接MySQL报错1045(28000):Access denied for user 'root'@'localhost'求助
解决Python连接MySQL时的1045访问拒绝错误
问题重现
使用以下Python代码连接MySQL:
try: with connect( host = "localhost", user = "root", password = "<password>", ) as connection: print(connection) except Error as E: print(E)
运行后抛出错误:
1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
确认密码正确,可通过该密码登录MySQL命令行客户端,但代码连接失败。
可能的解决方案
检查
connect函数的来源
确保导入的是mysql.connector库的connect函数,避免误导入其他库(如sqlite3)的同名函数导致参数不匹配。正确导入方式:from mysql.connector import connect, Error显式指定认证插件
MySQL 8.0+默认使用caching_sha2_password认证插件,部分Python驱动可能默认不支持。可在连接时指定兼容的插件:with connect( host="localhost", user="root", password="<password>", auth_plugin='mysql_native_password' ) as connection: print(connection)验证用户主机权限与认证方式
在MySQL命令行执行以下语句,查看root用户的权限配置:SELECT user, host, plugin FROM mysql.user WHERE user = 'root';如果
host仅为localhost且plugin为caching_sha2_password,可修改用户的认证插件:ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '<你的密码>'; FLUSH PRIVILEGES;替换
localhost为127.0.0.1
MySQL对localhost优先使用Unix socket(Linux/macOS)或命名管道(Windows)连接,127.0.0.1会强制使用TCP/IP连接,尝试修改host参数:host="127.0.0.1"处理密码中的特殊字符
若密码包含@、#、\等特殊字符,使用Python原始字符串(前缀加r)避免转义问题:password=r"<含特殊字符的密码>"
内容的提问来源于stack exchange,提问作者John Smith
相关产品推荐
相关产品推荐

