error mysql
MySQL Error 1045 - Access Denied
Understanding MySQL error 1045 - access denied for the specified user. Authentication failed due to wrong credentials or missing privileges.
What It Means
MySQL error 1045 (ER_ACCESS_DENIED_ERROR) means “Access denied for user ‘username’@‘host’ (using password: YES/NO).” The MySQL server rejected the connection because the credentials are invalid, the user does not exist for the connecting host, or the user lacks the required privileges.
Common Causes
- Wrong username or password
- User exists but not for the connecting host (e.g.,
'user'@'localhost'vs'user'@'%') - Password was recently changed
- Connecting without a password when one is required
- User account is locked
- Authentication plugin mismatch (e.g.,
caching_sha2_passwordvsmysql_native_password) - Environment variable with password has trailing whitespace or quotes
How to Fix
Verify credentials
# Test connection with explicit credentials
mysql -u root -p -h 127.0.0.1
# Check if the user exists
mysql -u root -p -e "SELECT user, host, plugin FROM mysql.user;"
Reset root password
# Stop MySQL
sudo systemctl stop mysql
# Start in safe mode
sudo mysqld_safe --skip-grant-tables &
# Connect without password
mysql -u root
# Reset the password
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword123!';
FLUSH PRIVILEGES;
# Restart MySQL normally
sudo systemctl restart mysql
Create or fix user access
-- Create a user for specific host
CREATE USER 'myapp'@'localhost' IDENTIFIED BY 'secure_password';
GRANT ALL PRIVILEGES ON mydb.* TO 'myapp'@'localhost';
-- Create a user for any host
CREATE USER 'myapp'@'%' IDENTIFIED BY 'secure_password';
GRANT ALL PRIVILEGES ON mydb.* TO 'myapp'@'%';
FLUSH PRIVILEGES;
-- Check existing grants
SHOW GRANTS FOR 'myapp'@'localhost';
Fix authentication plugin issues
-- MySQL 8.0+ uses caching_sha2_password by default
-- If your client doesn't support it, switch to mysql_native_password
ALTER USER 'myapp'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
FLUSH PRIVILEGES;
Fix in application code
// Node.js with mysql2
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: '127.0.0.1', // Use IP instead of 'localhost' to force TCP
user: 'myapp',
password: process.env.DB_PASSWORD, // Check for trailing whitespace!
database: 'mydb'
});
# Python with mysql-connector
import mysql.connector
connection = mysql.connector.connect(
host='127.0.0.1',
user='myapp',
password='secure_password',
database='mydb',
auth_plugin='mysql_native_password' # If needed
)
Docker MySQL access
# Docker: ensure MYSQL_ROOT_PASSWORD matches
docker run -e MYSQL_ROOT_PASSWORD=rootpass \
-e MYSQL_USER=myapp \
-e MYSQL_PASSWORD=apppass \
-e MYSQL_DATABASE=mydb \
mysql:8.0
Related Errors
- MySQL 1049 - Unknown database: Authenticated but the database doesn’t exist.
- MySQL 2002 - Connection refused: Cannot connect to the MySQL socket.
- MySQL 2003 - Can’t connect: Cannot reach the MySQL server.