You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地MySQL连接权限报错(1045)排查及解决方案

Fixing MySQL Access Denied Error in Python After Backup Restore

So here's the situation: you just restored a MySQL backup, and you can access the database perfectly fine via the terminal using sudo mysql (this command even starts MySQL if it's not running). But when you try to connect from your Python program, you hit this frustrating error:

OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: NO)")

You’ve tried both entering your root password and leaving it blank—neither approach works. Sound familiar?

The Simple Fix That Worked

Turns out the solution is easier than you might expect: replace localhost with 127.0.0.1 in your Python database connection string.

Here’s why this works: MySQL handles localhost connections differently—it uses Unix socket authentication instead of TCP/IP. When you run sudo mysql, you’re leveraging the socket permissions granted to the root system user, which your Python process doesn’t have access to. Switching to 127.0.0.1 forces the connection to use TCP/IP, which aligns with the standard password-based authentication setup for your MySQL root user.

For example, if your original connection code looked like this:

import mysql.connector
# This would throw the access denied error
cnx = mysql.connector.connect(user='root', host='localhost')

Update it to this:

import mysql.connector
# This should connect successfully
cnx = mysql.connector.connect(user='root', host='127.0.0.1', password='your_root_password')

That’s it—this change should get your Python app connected to MySQL without any more access denied issues.

内容的提问来源于stack exchange,提问作者lpt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:42:31