本地MySQL连接权限报错(1045)排查及解决方案
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

