Дата: 25.11.2013
Автор: Василий Лукьянчиков , vl (at) sqlinfo (dot) ru
Статистика форума SQLinfo показывает, что одной из наиболее популярных проблем является ошибка mysql №1045 (ошибка доступа).
Текст ошибки содержит имя пользователя, которому отказано в доступе, компьютер, с которого производилось подключение, а также ключевое слово YES или NO, которые показывают использовался ли при этом пароль или была попытка выполнить подключение с пустым паролем.
Типичные примеры:
ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES) — сервер MySQL
— сообщает, что была неудачная попытка подключения с локальной машины пользователя с именем root и
— не пустым паролем.
ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: NO) — отказано в
— доступе с локальной машины пользователю с именем root при попытке подключения с пустым паролем.
ERROR 1045 (28000): Access denied for user ‘ODBC’@‘localhost’ (using password: NO) — отказано в
— доступе с локальной машины пользователю с именем ODBC при попытке подключения с пустым паролем.
Причина возникновения ошибки 1045
Как ни банально, но единственная причина это неправильная комбинация пользователя и пароля. Обратите внимание, речь идет о комбинации пользователь и пароль, а не имя пользователя и пароль. Это очень важный момент, так как в MySQL пользователь характеризуется двумя параметрами: именем и хостом, с которого он может обращаться. Синтаксически записывается как ‘имя пользователя’@’имя хоста’.
Таким образом, причина возникновения MySQL error 1045 — неправильная комбинация трех параметров: имени пользователя, хоста и пароля.
В качестве имени хоста могут выступать ip адреса, доменные имена, ключевые слова (например, localhost для обозначения локальной машины) и групповые символы (например, % для обозначения любого компьютера кроме локального). Подробный синтаксис смотрите в документации
Замечание: Важно понимать, что в базе не существует просто пользователя с заданным именем (например, root), а существует или пользователь с именем root, имеющий право подключаться с заданного хоста (например, root@localhost) или даже несколько разных пользователей с именем root (root@127.0.0.1, root@webew.ru, root@’мой домашний ip’ и т.д.) каждый со своим паролем и правами.
Примеры.
1) Если вы не указали в явном виде имя хоста
GRANT ALL ON publications.* TO ‘ODBC’ IDENTIFIED BY ‘newpass’;
то у вас будет создан пользователь ‘ODBC’@’%’ и при попытке подключения с локальной машины вы получите ошибку:
ERROR 1045 (28000): Access denied for user ‘ODBC’@‘localhost’ (using password: YES)
так как пользователя ‘ODBC’@’localhost’ у вас не существует.
2) Другой первопричиной ошибки mysql 1045 может быть неправильное использование кавычек.
CREATE USER ‘new_user@localhost’ IDENTIFIED BY ‘mypass’; — будет создан пользователь ‘new_user@localhost’@’%’
Правильно имя пользователя и хоста нужно заключать в кавычки отдельно, т.е. ‘имя пользователя’@’имя хоста’
3) Неочевидный вариант. IP адрес 127.0.0.1 в имени хоста соответствует ключевому слову localhost. С одной стороны, root@localhost и ‘root’@’127.0.0.1’ это синонимы, с другой, можно создать двух пользователей с разными паролями. И при подключении будет выбран тот, который распологается в таблице привелегий (mysql.user) раньше.
4) Аккаунт с пустым именем пользователя трактуется сервером MySQL как анонимный, т.е. позволяет подключаться пользователю с произвольным именем или без указания имени.
Например, вы создали пользователя »@localhost с пустым паролем, чтобы каждый мог подключиться к базе. Однако, если при подключении вы укажите пароль отличный от пустого, то получите ошибку 1045. Как говорилось ранее, нужно совпадение трех параметров: имени пользователя, хоста и пароля, а пароль в данном случае не совпадает с тем, что в базе.
Что делать?
Во-первых, нужно убедиться, что вы используете правильные имя пользователя и пароль. Для этого нужно подключиться к MySQL с правами администратора (если ошибка 1045 не дает такой возможности, то нужно перезапустить сервер MySQL в режиме —skip-grant-tables), посмотреть содержимое таблицы user служебной базы mysql, в которой хранится информация о пользователях, и при необходимости отредактировать её.
Пример.
SELECT user,host,password FROM mysql.user;
+—————+——————+——————————————-+
| user | host | password |
+—————+——————+——————————————-+
| root | house-f26710394 | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |
| aa | localhost | *196BDEDE2AE4F84CA44C47D54D78478C7E2BD7B7 |
| test | localhost | |
| new_user | % | |
| | % | *D7D6F58029EDE62070BA204436DE23AC54D8BD8A |
| new@localhost | % | *ADD102DFD6933E93BCAD95E311360EC45494AA6E |
| root | localhost | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |
+—————+——————+——————————————-+
Если изначально была ошибка:
-
ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES)
значит вы указывали при подключении неверный пароль, так как пользователь root@localhost существует. Сам пароль храниться в зашифрованном виде и его нельзя узнать, можно лишь задать новый
SET PASSWORD FOR root@localhost=PASSWORD(‘новый пароль’);
-
ERROR 1045 (28000): Access denied for user ‘ODBC’@‘localhost’ (using password: YES)
в данном случае в таблице привилегий отсутствует пользователь ‘ODBC’@’localhost’. Его нужно создать, используя команды GRANT, CREATE USER и SET PASSWORD.
Экзотический пример. Устанавливаете новый пароль для root@localhost в режиме —skip-grant-tables, однако после перезагрузки сервера по прежнему возникает ошибка при подключении через консольный клиент:
ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES)
Оказалось, что было установлено два сервера MySQL, настроенных на один порт.
phpmyadmin
При открытии в браузере phpmyadmin получаете сообщение:
Error
MySQL said:
#1045 — Access denied for user ‘root’@’localhost’ (using password: NO)
Connection for controluser as defined in your configuration failed.
phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server.
Ни логина, ни пароля вы не вводили, да и пхпадмин их нигде требовал, сразу выдавая сообщение об ошибке. Причина в том, что данные для авторизации берутся из конфигурационного файла config.inc.php Необходимо заменить в нем строчки
$cfg[‘Servers’][$i][‘user’] = ‘root’; // MySQL user
$cfg[‘Servers’][$i][‘password’] = »; // MySQL password (only needed
на
$cfg[‘Servers’][$i][‘user’] = ‘ЛОГИН’;
$cfg[‘Servers’][$i][‘password’] = ‘ПАРОЛЬ’
Установка новой версии
Устанавливаете новую версию MySQL, но в конце при завершении конфигурации выпадает ошибка:
ERROR Nr. 1045
Access denied for user ‘root’@‘localhost’ (using password: NO)
Это происходит потому, что ранее у вас стоял MySQL, который вы удалили без сноса самих баз. Если вы не помните старый пароль и вам нужны эти данные, то выполните установку новой версии без смены пароля, а потом смените пароль вручную через режим —skip-grant-tables.
P.S. Статья написана по материалам форума SQLinfo, т.е. в ней описаны не все потенциально возможные случаи возникновения ошибки mysql №1045, а только те, что обсуждались на форуме. Если ваш случай не рассмотрен в статье, то задавайте вопрос на форуме SQLinfo
Вам ответят, а статья будет расширена.
Дата публикации: 25.11.2013
© Все права на данную статью принадлежат порталу SQLInfo.ru. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.
When you’re knee-deep in managing a WordPress site, coming across a MySQL 1045 error can throw a wrench in your workflow. It’s like you’re trying to get into a club, but the bouncer isn’t letting you in because you don’t have the VIP pass. Essentially, this error pops up when your MySQL server thinks you don’t have the keys to the kingdom—either your password’s wrong, or you’re missing the necessary permissions to access the database.
By understanding the MySQL 1045 Error and exploring a few troubleshooting methods, you can find your way back in no time. Let’s dive into the what, why, and how of fixing this common yet frustrating hiccup.
What is the MySQL error 1045?
In its simplest form, the MySQL 1045 Error signals that you are not authorized to access the database from your current location, often referred to as “localhost.”
[root@localhost ~]# mysql -u root -p Enter password: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
This error manifests in various ways but commonly appears when trying to interact with your WordPress database, a critical component for managing site content. While similar database systems like MariaDB and SQLite also sometimes produce this error, you won’t see error 1045 on databases like MongoDB since they don’t use MySQL.
While this error may show up in a slightly different variation, it often appears as ‘ERROR 1045: Access denied’.
This error means one thing: MySQL isn’t convinced you should be there. Maybe you’re using the wrong password, your username doesn’t have the right permissions, or you’re trying to access the database from an unexpected host.
Causes of error 1045 MySQL
The reasons behind the error 1045 MySQL are as varied as the flavors of ice cream at your favorite parlor.
Insufficient permissions: Without the right permissions, accessing the MySQL database is a no-go.
User doesn’t exist: If the server hasn’t heard of you, you’re not getting in.
Incorrect login credentials: Mixing up passwords is an easy mistake, especially with multiple accounts in the mix.
Wrong host or port: Unless you tell MySQL what host to connect with, it will try to connect with localhost. This may not be the correct host. Likewise for ports, too.
Bash interference: Sometimes, the command line gets a bit too involved, messing with special characters in your password.
SSL requirements: Without the necessary Secure Sockets Layer (SSL) certificate, access might be blocked.
Identifying the cause of the error is key and helps point you to the right method to fix the error. If you’re still in the dark, here are four methods you can use to troubleshoot.
Say goodbye to website errors
Achieve peace of mind with 99.99% uptime on 10Web Managed
WordPress Hosting, powered by Google Cloud.
Fixing error 1045
Start by verifying that the user has sufficient permissions and that the credentials are correct.
1. Verify that the user has the necessary privileges
First things first, check if your “root” user has the correct permissions. This involves diving into the terminal and running a few commands to peek at the user’s permissions. If you’re using phpMyAdmin, it’s a matter of logging into your hosting account and navigating through the user accounts section.
Through Terminal:
- Open your terminal. Depending on your operating system, this could be Terminal on macOS or Command Prompt/Powershell on Windows.
- Connect to your server via SSH by entering the command: `ssh username@ipaddress`. Replace `username` with your actual username and `ipaddress` with your server’s IP address.
- Access MySQL by typing: `mysql -uroot -p`. You’ll be prompted to enter the root password.
- Grant privileges with the command:
GRANT ALL PRIVILEGES ON . TO 'root'@'localhost' IDENTIFIED BY 'password';
Replace `password` with a secure password of your choice. This grants all privileges to the root user.
Through phpMyAdmin:
Accessing phpMyAdmin may vary between hosting providers. The process typically involves accessing it from your control panel or hosting dashboard’s databases area.
For example, at 10Web, you would click on Hosting Services > Credentials and look for the Open MySQL button in the Database Access section.
- Log into your hosting account and access phpMyAdmin from the dashboard.
- Navigate to the User Accounts tab.
- Find the user in question, often “root,” and click on Edit Privileges.
- Select the appropriate privileges or simply check all to grant full access.
- Save changes by clicking on Go.
2. Make sure you’re using the correct username and password
It might sound too simple, but ensuring you’re using the right username and password is crucial. Peek into the `wp-config.php` file to verify these credentials. If your memory’s a bit hazy, cPanel or your hosting dashboard can help jog it.
- Access your site’s root directory through your host’s control panel or via SFTP.
- Locate the wp-config.php file. This is typically found in the public_html directory.
- Open wp-config.php with a text editor.
- Verify the DB_USER and DB_PASSWORD values. Ensure they match the username and password you have set for your MySQL database. If incorrect, update them with the correct credentials and save the file.
3. Reset your password
If your password’s triggering the error 1045, resetting it can pave the way back into MySQL’s good graces. Access phpMyAdmin, find the user whose password needs a refresh, and make the change. Remember, encrypting the new password with MD5 adds an extra layer of security.
Through phpMyAdmin:
- Open phpMyAdmin and select your WordPress database from the sidebar.
- Navigate to the wp_users table by clicking on it.
- Locate the user whose password you wish to reset and click on the Edit link beside their row.
- Find the user_pass field. In the Value column, enter your new password.
- Select MD5 in the Function dropdown. This encrypts your password.
- Click Go to save your new, encrypted password.
4. Make sure the MySQL server is listening to the correct port
Finally, ensuring MySQL is listening on the right port can clear up any misunderstanding. The default port is 3306, but a quick check and potential tweak might be in order if your setup differs.
- Check if MySQL is running by opening your terminal and entering:
systemctl status mysql
If it’s not running, start it with:
systemctl start mysql
- Access MySQL by typing `mysql -uroot -p` in your terminal. Enter your root password when prompted.
- Verify the port MySQL is listening on by executing:
SHOW VARIABLES LIKE 'port';
- This should return 3306, the default MySQL port. If it’s different and needs to be changed, proceed to the next steps.
- Open the MySQL configuration file for editing. This file is usually located at `/etc/mysql/mysql.conf.d/mysqld.cnf` on Linux.
- Search for the `port` setting in the configuration file and change it to 3306 if it’s not already set to that.
- Restart MySQL to apply the changes by running:
systemctl restart mysql
By following these detailed instructions, you should be able to effectively address the MySQL 1045 Error, whether it’s due to privilege issues, incorrect login credentials, a need to reset your password, or ensuring the server is listening on the correct port.
Wrapping up
The MySQL 1045 Error can be a headache, but it’s not insurmountable. Whether it’s a permissions issue, a mix-up with login credentials, or a technical snag, there’s a solution at hand. By methodically addressing each potential cause, you can regain access to your MySQL database and get back to the business of managing your WordPress site with minimal disruption.
Say goodbye to website errors
Achieve peace of mind with 99.99% uptime on 10Web Managed
WordPress Hosting, powered by Google Cloud.
-
Written By
-
Approved By
Mithilesh Tata
-
Updated on
January 9th, 2024 -
Reading Time:
4 minutes
Summary: The MySQL Error typically occurs when you have to set out access to your MySQL database through WordPress. The request will be denied if the server doesn’t think you are authorized to perform the action. Maybe you are using the wrong password or you have the required permissions. So, there are plenty of ways to fix the MySQL error 1045 (28000). In this blog post, we will talk about the verified solutions to resolve MySQL error 1045. Additionally, we have the MySQL Database Recovery software which is a prominent tool to recover corrupted MySQL databases. Along with this, we take a look at some restrictions for which users want to resolve this error. Let’s get started. Download Now Purchase Now
What is MySQL Error 1045 (28000)
MySQL is a relational database management system that stores and provides access to data points that are related to one another. MySQL uses Structured Query Language to add, access, and manage content in a database. However, many times MySQL error 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES) appears.
Reasons for MySQL Error 1045 (28000)
In MySQL, the error 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES) can appear because of the following reasons:
- When the host is not the admin.
- It might happen that the user does not exist on the server.
- Recheck the Login credentials: username and password.
So, here I will explain how to fix the error by providing a solution to the given problems. After that, I will justify the query using a utility.
Fixing the Error 1045 (28000): Access Denied for User ‘root’@’localhost’ (using password: YES) on Windows
Now, we will look into the problem-solving steps for the reasons stated above. Follow the methods given below:
1. When the Host is Not the Admin
The issue 1045 access denied for user localhost’ (using password: YES) can also occur when a person is trying to log in from another device. Try to log in from the same device in which you were earlier using the MySQL service.
2. The User Does Not Exist on the Server
The user may not exist on the same server that your MySQL is using. This can cause the error: Access denied for user ‘root’@’localhost’ (using password: YES). So, to solve the issue user must be on the MySQL server.
3. Recheck the Login Credentials: Username and Password
While Login to the MySQL server users may encounter the given error 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES). This could mean that the password that you entered is wrong, so, to resolve the issue, follow the steps below:
- Open /etc/mysql/my.cnf path from the SSH Server.
- Then add the skip-grant-tables [mysqld] section.
Note: There is no other way to log in besides skip-grant tables. So, anyone can log in from anywhere and can do anything on the database. Skip-grant-tables is a dangerous option. So, we will remove this at the end.
- Restart, MySQL service using the command: service mysql restart
So, now when you log in, ‘skip-grant-tables’ is configured in MySQL.
- Log in to MySQL using: the MySQL -u root command.
- Then, flush the privileges by using: mysql> flush privileges;
- Here you can set a new password using the command: UPDATE user SET
Password=PASSWORD (‘my_password’) where USER=‘root’;
FLUSH PRIVILEGES;
- After that, remove the skip-grant-tables section from /etc/mysql/my.cnf
- At last, restart and log in to the MySQL service using the new password.
You can check your error 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES) is now fixed.
4. Grant Privileges
This error can also occur when there are no global privileges provided. So, to add the privileges use the given command:
GRANT ALL PRIVILEGES ON THE database.* TO ‘user’@‘localhost;’
Now, you can check your status for the error. If the error is still not resolved, then you must use the MySQL Database Recovery tool. In the next section, I will brief you on insights into this utility.
MySQL Database Recovery Utility to Recover MySQL Database
MySQL Database Recovery is a prominent tool to recover corrupted MySQL databases. Using the MySQL Database Recovery software, you can restore all your database objects such as views, tables, triggers, and more. Users can recover data from InnoDB and My ISAM engines with ease. The software maintains data integrity throughout the recovery process of corrupt SQL databases using smart algorithms. MySQL database recovery software can also solve common errors in MySQL.
Conclusion
So, this was the MySQL error 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES). I have provided quick solutions to fix the error. Work becomes hard when such errors appear and cause trouble while Logging. So, follow all the steps to resolve the error. Moreover, mentioned a quick solution to recover MySQL database using (MySQL Database Recovery) tool. It helps to maintain data integrity throughout the recovery process. To recover from such issues in future preferences. The utility will help you to fix MySQL error 1045.
Related Post
During our work in support, we see this again and again: “I try to connect to MySQL and am getting a 1045 error”, and most times it comes accompanied with “…but I am sure my user and password are OK”. So we decided it was worth showing other reasons this error may occur.
MySQL 1045 error Access Denied triggers in the following cases:
1) Connecting to wrong host:
[engineer@percona]# mysql -u root -psekret mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES) |
If not specifying the host to connect (with -h flag), MySQL client will try to connect to the localhost instance while you may be trying to connect to another host/port instance.
Fix: Double check if you are trying to connect to localhost, or be sure to specify host and port if it’s not localhost:
[engineer@percona]# mysql -u root -psekret -h <IP> -P 3306 |
2) User does not exist:
[engineer@percona]# mysql -u nonexistant -psekret -h localhost mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES) |
Fix: Double check if the user exists:
mysql> SELECT User FROM mysql.user WHERE User=‘nonexistant’; Empty set (0.00 sec) |
If the user does not exist, create a new user:
mysql> CREATE USER ‘nonexistant’@‘localhost’ IDENTIFIED BY ‘sekret’; Query OK, 0 rows affected (0.00 sec) |
3) User exists but client host does not have permission to connect:
[engineer@percona]# mysql -u nonexistant -psekret mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES) |
Fix: You can check to see which host user/host MySQL allows connections with the following query:
mysql> SELECT Host, User FROM mysql.user WHERE User=‘nonexistant’; +———————+———————+ | Host | User | +———————+———————+ | 192.168.0.1 | nonexistant | +———————+———————+ 1 row in set (0.00 sec) |
If you need to check from which IP the client is connecting, you can use the following Linux commands for server IP:
[engineer@percona]# ip address | grep inet | grep -v inet6 inet 127.0.0.1/8 scope host lo inet 192.168.0.20/24 brd 192.168.0.255 scope global dynamic wlp58s0 |
or for public IP:
[engineer@percona]# dig +short myip.opendns.com @resolver1.opendns.com 177.128.214.181 |
You can then create a user with correct Host (client IP), or with ‘%’ (wildcard) to match any possible IP:
mysql> CREATE USER ‘nonexistant’@‘%’ IDENTIFIED BY ‘sekret’; Query OK, 0 rows affected (0.00 sec) |
4) Password is wrong, or the user forgot his password:
[engineer@percona]# mysql -u nonexistant -pforgotten mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES) |
Fix: Check and/or reset password:
You cannot read user passwords in plain text from MySQL as the password hash is used for authentication, but you can compare hash strings with “PASSWORD” function:
mysql> SELECT Host, User, authentication_string, PASSWORD(‘forgotten’) FROM mysql.user WHERE User=‘nonexistant’; +———————+———————+——————————————————————+——————————————————————+ | Host | User | authentication_string | PASSWORD(‘forgotten’) | +———————+———————+——————————————————————+——————————————————————+ | 192.168.0.1 | nonexistant | *AF9E01EA8519CE58E3739F4034EFD3D6B4CA6324 | *70F9DD10B4688C7F12E8ED6C26C6ABBD9D9C7A41 | | % | nonexistant | *AF9E01EA8519CE58E3739F4034EFD3D6B4CA6324 | *70F9DD10B4688C7F12E8ED6C26C6ABBD9D9C7A41 | +———————+———————+——————————————————————+——————————————————————+ 2 rows in set, 1 warning (0.00 sec) |
We can see that PASSWORD(‘forgotten’) hash does not match the authentication_string column, which means password string=’forgotten’ is not the correct password to log in. Also, in case the user has multiple hosts (with different password), he may be trying to connect using the password for the wrong host.
In case you need to override the password you can execute the following query:
mysql> set password for ‘nonexistant’@‘%’ = ‘hello$!world’; Empty set (0.00 sec) |
5) Special characters in the password being converted by Bash:
[engineer@percona]# mysql -u nonexistant -phello$!world mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES) |
Fix: Prevent bash from interpreting special characters by wrapping password in single quotes:
[engineer@percona]# mysql -u nonexistant -p’hello$!world’ mysql: [Warning] Using a password on the command line interface can be insecure ... mysql> |
6) SSL is required but the client is not using it:
mysql> create user ‘ssluser’@‘%’ identified by ‘sekret’; Query OK, 0 rows affected (0.00 sec) mysql> alter user ‘ssluser’@‘%’ require ssl; Query OK, 0 rows affected (0.00 sec) ... [engineer@percona]# mysql -u ssluser -psekret mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘ssluser’@‘localhost’ (using password: YES) |
Fix: Adding –ssl-mode flag (–ssl flag is deprecated but can be used too)
[engineer@percona]# mysql -u ssluser -psekret —ssl-mode=REQUIRED ... mysql> |
You can read more in-depth on how to configure SSL in MySQL in the blog post about “Setting up MySQL SSL and Secure Connections” and “SSL in 5.6 and 5.7“.
7) PAM backend not working:
mysql> CREATE USER ‘ap_user’@‘%’ IDENTIFIED WITH auth_pam; Query OK, 0 rows affected (0.00 sec) ... [engineer@percona]# mysql -u ap_user -pap_user_pass mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘ap_user’@‘localhost’ (using password: YES) |
Fix: Double check user/password is correct for the user to authenticate with the PAM currently being used.
In my example, I am using Linux shadow files for authentication. In order to check if the user exists:
[engineer@percona]# cat /etc/passwd | grep ap_user ap_user:x:1000:1000::/home/ap_user:/bin/bash |
To reset password:
[engineer@percona]# sudo passwd ap_user Changing password for user ap_user. New password: |
Finally, if you are genuinely locked out and need to circumvent the authentication mechanisms in order to regain access to the database, here are a few simple steps to do so:
- Stop the instance
- Edit my.cnf and add skip-grant-tables under [mysqld] (this will allow access to MySQL without prompting for a password). On MySQL 8.0, skip-networking is automatically enabled (only allows access to MySQL from localhost), but for previous MySQL versions it’s suggested to also add –skip-networking under [mysqld]
- Start the instance
- Access with root user (mysql -uroot -hlocalhost);
-
Issue the necessary GRANT/CREATE USER/SET PASSWORD to correct the issue (likely setting a known root password will be the right thing: SET PASSWORD FOR ‘root’@’localhost’ = ‘S0vrySekr3t’). Using grant-skip-tables won’t read grants into memory and GRANT/CREATE/SET PASSWORD statements won’t work straight away. First, you need to execute “FLUSH PRIVILEGES;” before executing any GRANT/CREATE/SET PASSWORD statement, or you can modify mysql.users table with a query which modifies the password for User and Host like “UPDATE mysql.user SET authentication_string=
PASSWORD(‘newpwd’) WHERE User=’root’ and Host=’localhost’;” - Stop the instance
- Edit my.cnf and remove skip-grant-tables and skip-networking
- Start MySQL again
- You should be able to login with root from the localhost and do any other necessary corrective operations with root user.
Learn more about Percona Server for MySQL
MySQL users often face an issue called Error 1045 (28000) access denied for user ‘root’@’localhost’ (using password: yes). This usually occurs when you enter an incorrect password or password for your database. Fixing these credentials can resolve this error in no time.
In this article, we will look at the ways to resolve this error.
How to fix “Error 1045 (28000) access denied for user ‘root’@’localhost’ (using password: yes)”?
The error looks something like this —
mysql -uroot -proot
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
It arises when you perform a fresh installation of MySQL and try to login with a password. The default password of MySQL is blank () (i.e. empty string).
So, you can login to the MySQL server using the same password.
Example
>mysql -uroot -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 10.4.11-MariaDB mariadb.org binary distribution
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the current input statement.
MariaDB [(none)]>
The best practice is to change the password after the new installation.
Set root user password
You must set the root user password after performing the new installation. Here is the code to set it –
Login as user root with blank password
>mysql -u root
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'abc';
Now the new password for root user is abc.
How to fix the Error 1045 (28000)?
Let us look at the ways to fix this problem –
-
Enter the correct credentials
The primary method to fix this error is to enter the correct username and password using the following command –
mysql –u username –p
-
Ensure the user is correct
Sometimes, the user you might be trying to access does not exist on the MySQL server. You can check if the user exists using the following code-
MariaDB [(none)]> select user from mysql.user where user like '%root%';
+------+
| User |
+------+
| root |
| root |
| root |
+------+
3 rows in set (0.001 sec)
If the user does not exist, create it with the desired username.
-
Enter the correct host name
You might be trying to access the server from a host that is different from the defined host name. You will encounter Error 1045 in this case. You can use this code to view details of the user –
To fix this, you can update the host name for the user using the code below –
mysql> mysql -u root -pabc -h <IP> -P 3306
You might encounter the error in due to the following scenarios –
Entered wrong password
>mysql -uroot -pssssss
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
Host doesn’t not have permission to connect database
This is a very common error that occurs while connecting to a remote database. While connecting to such a database we need to give access to the HOST IP ADDRESS to connect to it.
This is the IP Address of the source system which connects to the database server.
If access is not given, then run the given command –
CREATE USER ‘dbuser1’@'< Host IP >’ IDENTIFIED VIA mysql_native_password USING ‘***’;GRANT ALL PRIVILEGES ON *.* TO ‘dbuser1’@'< Host IP >’ REQUIRE NONE WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;
Conclusion
Apart from all this, make sure the host contains the correct IP address and host name, to avoid the Error 1045 (28000) access denied for user ‘root’@’localhost’ (using password: yes).