ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
Nobody remembers the root password, or the person who set it has left. Or it's a brand-new Ubuntu install where the password you typed during setup doesn't seem to work. Here's how to get back in safely on MySQL 8.x (and, with small differences, MariaDB).
First: maybe root doesn't use a password at all
On Debian and Ubuntu packages (and MariaDB on many distributions), root@localhost authenticates with the auth_socket / unix_socket plugin: you're let in if you're the operating system's root user, and any password is ignored.
sudo mysql # no -p, no password
If that works, you're in. Check how accounts authenticate:
SELECT user, host, plugin FROM mysql.user;
It's usually best to leave root on socket auth and create a separate admin user for password logins:
CREATE USER 'admin'@'localhost' IDENTIFIED BY 'a-long-random-password';
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' WITH GRANT OPTION;
Reset a forgotten password with --init-file (recommended)
This is the method in the MySQL manual. The server runs a one-time SQL file at startup, with no window where authentication is disabled:
