Mysql error 1045 28000 access denied for user odbc localhost using password no

when am trying to open mysql in windows cmd by typing mysql. the following error is occuring. ERROR 1045 (28000): Access denied for user ODBC@localhost (using password: NO) And then by looking si...

when am trying to open mysql in windows cmd by typing mysql. the following error is occuring.

ERROR 1045 (28000): Access denied for user ODBC@localhost (using password: NO)

And then by looking similar queries i somehow got a temporary solution by using
C:> mysql -u root -p and then typing the password, mysql is working. But when i close and open, the same problem is recurring.

One more thing is that i have created a user ‘admin’. but when am trying to open mysql using the command C:> mysql --user=admin --password=root, the following error is occuring:

C:Usersabhay kumar>mysql --user=admin --password=root
ERROR 1045 (28000): Access denied for user 'admin'@'localhost' (using password:NO)

Any help will great

asked May 30, 2014 at 9:00

user3690599's user avatar

1

for some reason, the ODBC user is the default username under windows even if you didn’t create that user at setup time. simply typing

mysql

without specifying a username will attempt to connect with the non-existent ODBC username, and give:

Error 1045 (28000): Access denied for user ‘ODBC’@’localhost’ (using password: NO)

Instead, try specifying a username that you know, for example:

mysql -u root -p

where -u root specified the username root and -p will make the command prompt for a password.

jotik's user avatar

jotik

16.6k12 gold badges55 silver badges118 bronze badges

answered Mar 18, 2015 at 1:42

Nish's user avatar

NishNish

1,4411 gold badge9 silver badges6 bronze badges

4

You need to create an user «ODBC» for MySql with no password. Do that in PHPMyAdmin. That will solve your problem.

But remember, if it’s only your local development environment, no problem. It’ll create a serious security hole in your production environment.

User ODBC with no password

Problem Solved

answered May 29, 2015 at 6:47

Imtiaz's user avatar

ImtiazImtiaz

2,4242 gold badges24 silver badges32 bronze badges

2

I tried this and it worked:

C:cd MySQL installed pathMySQL -uyourusername -pyourpassword

James's user avatar

James

4,6155 gold badges36 silver badges48 bronze badges

answered Jun 6, 2015 at 13:58

ravi ranjan's user avatar

C:Usersabhay kumar>mysql --user=admin --password=root..

This command is working for root user..you can access mysql tool from any where using command prompt..

C:Userslelaprasad>mysql --user=root --password=root
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 4
Server version: 5.5.47 MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.

Tunaki's user avatar

Tunaki

130k46 gold badges326 silver badges414 bronze badges

answered Apr 12, 2016 at 11:39

Madhu Baswani's user avatar

I know it’s been three years since this was asked, but I just figured out this problem for myself. I was using into outfile and getting the error. When I commented out this part of the query, it worked.

The FILE privilege is separate from all the others and must be granted to the user running the script.

GRANT FILE ON *.* TO 'asdfsdf'@'localhost';

Mike Mackintosh's user avatar

answered Jun 23, 2017 at 20:18

DickoVan's user avatar

1

Just create a file my.ini file in installation dir and have the below config as part of this file to solve this permanently.

[mysql]
user=root
password=root

answered Aug 22, 2018 at 14:32

varra's user avatar

varravarra

1648 bronze badges

1

Try this command:
mysql -uroot -p
then it will ask for password
enter root as the password.

answered Mar 28, 2022 at 19:55

Akshay Srivastava's user avatar

If you are using dj-database-url check the schema in your DATABASES

https://github.com/kennethreitz/dj-database-url

MySQL is

'default': dj_database_url.config(default='mysql://USER:PASSWORD@localhost:PORT/NAME') 

It solves the same error even without the PORT

You set the password with:

mysql -u user -p 

answered Aug 31, 2017 at 21:21

Rider 's user avatar

Rider Rider

396 bronze badges

Try using following command it work.

mysql --user=root --password=root_password

answered Apr 12, 2019 at 5:52

Know Group's user avatar

Why you can’t just use mysqlsh?

PS C:UsersarturDesktop> mysqlsh --user root
MySQL Shell 8.0.17

Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates.
Other names may be trademarks of their respective owners.

Type 'help' or '?' for help; 'quit' to exit.
Creating a session to 'root@localhost'
Fetching schema names for autocompletion... Press ^C to stop.
Your MySQL connection id is 13 (X protocol)
Server version: 8.0.17 MySQL Community Server - GPL
No default schema selected; type use <schema> to set one.
 MySQL  localhost:33060+ ssl  JS >

mysqlsh on windows terminal (pic)

mate00's user avatar

mate00

2,5995 gold badges25 silver badges34 bronze badges

answered Aug 13, 2019 at 11:50

Artur Paszek's user avatar

1

I have found the answer for this:

enter mysql -u user -p

this will leads to Enter Password .

Then enter the password which you have given…

below is the example:
*****C:Usersadmin>mysql -u root -p

**Enter password: **********************

Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 26
Server version: 8.0.31 MySQL Community Server — GPL

This is worked for me

answered Nov 22, 2022 at 7:00

Ajay HP's user avatar

  1. open command line (run as admin)
  2. go into Mysql server bin folder
  3. run command:
    mysqldump -u root -p mydbscheme > mydbscheme_dump.sql
  4. give your password here against root.

It will work perfect !!

Stephen Rauch's user avatar

Stephen Rauch

46.8k31 gold badges109 silver badges131 bronze badges

answered Aug 2, 2017 at 5:36

Muhammad's user avatar

You can create user with no password in phpmyadmin and it solves the problem!
Lebbar Abdelhadi,

answered May 11, 2020 at 13:33

abdelhadi lebbar's user avatar

It seems like You haven’t set the Mysql server path, Set Environment Variable For MySql Server. Then restart the command prompt and enter mysql -u root-p then it asks for a password enter it.
Thank you.
Happy learning!

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

answered Sep 13, 2020 at 4:37

pavankumar's user avatar

pavankumarpavankumar

3175 silver badges12 bronze badges

You can connect to SQL from a python Jupiter notebook using this syntax:

import  mysql.connector as conn
conn.connect(host = 'localhost', user = 'root', passwd = 'xxx')

xxx = your password for MySQL
user = your MySQL user name, which might be different from root. Check your MySQL userid, and change it accordingly.

SherylHohman's user avatar

SherylHohman

15.7k17 gold badges87 silver badges91 bronze badges

answered Jan 11, 2022 at 12:51

SantoshKumarPuvvada's user avatar

Let me what worked for me —

Step 1 — In cmd, give a command

set path=%PATH%;set path=%PATH%;C:Program FilesMySQLMySQL Server 8.0bin

[Note — make sure you are replacing ‘C:Program FilesMySQLMySQL
Server’
with your ‘MySQL server path’ above]

Step 2 — type,

mysql -u user -p

👆🏽 This will ask for password and you are good to go but sometimes
it does not work…

Then try this 👇🏽

Alternative of Step 2 —

--user=root --password=1234

👆🏽Must replace your username and password with above

Step 3 — Check out by

mysql --version

I hope this may help…🤞🏽👍🏽

answered Nov 2, 2022 at 9:02

Aditya Gaikwad's user avatar

i entered in Mysql Workbench and i changed the password. It seem the password was expired. it works!

answered Oct 9, 2018 at 8:27

samivic's user avatar

samivicsamivic

1,12813 silver badges13 bronze badges

I encountered this problem today. I tried mysql -u root -p, but it doesn’t work.
I restarted the mysql service by two commands:
net stop mysql and net start mysql
then tried the command mysql. It worked.

techspider's user avatar

techspider

3,37012 gold badges36 silver badges60 bronze badges

answered Jun 13, 2016 at 14:27

W.hr's user avatar

Дата: 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. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.

Это может быть, если пароль не был задан при установке.

Порядок действий для установки/смены пароля root в mysql следующий:

1. Остановить mysql:
sudo service mysql stop

2. Запустить сервис со следующими параметрами:
sudo mysqld --skip-grant-tables --user=root

Если выдал ошибку то в файле /etc/mysql/mysql.conf.d/mysqld.cnf в секцию [mysqld] добавить строчкуskip-grant-tables и выполнить sudo service mysql restart

3. После этого подключиться к mysql командой:
mysql -u root

4. Обновить пароль root’a:

UPDATE mysql.user SET authentication_string=PASSWORD('<новый пароль>'), plugin='mysql_native_password' WHERE User='root' AND Host='localhost';    
FLUSH PRIVILEGES;

5. И перезапустить сервис:
sudo service mysql restart
Если на шаге 2 вы добавляли skip-grant-tables в /etc/mysql/mysql.conf.d/mysqld.cnfудалить эту строчку.

Подробнее в Русскоязычной документации Ubuntu

Пароль по умолчанию пустой.
Возможно, вы неправильно набрали команду. Скопируйте именно эту: mysql -u root -p. На запрос пароля надо просто нажать Enter.

Попробуйте запустить mysql_secure_installation.

Если все равно не пускает — поищите пароль в логе: sudo grep 'temporary password' /var/log/mysqld.log.

Если и этот вариант не подошел — возможно, устанавливаете из какого-то левого репозитория. Удалите sudo apt-get purge mysql*, выключите левые репозитории и установите заново sudo apt-get install mysql-server.

Он пишет что пароль не нужен.

Тут два варианта, ИМХО.
1) Вы что-то не так поняли из курса:
2) Составитель курса что-то упустил.
В любом случае или стоило бы сюда ссылку кинуть на этот курс или писать составителю.

По проблеме. Сервер mysql пишет вам, что пользователю ‘root’ доступ закрыт. Как мне кажется, нужно вначале создать бд, применить схему и там создастся пользователь, с данными которого вы подключитесь к бд. А слова «Using password: NO» означает лишь, что пароль и не использовался.

MySQL 1045 error Access DeniedDuring 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:

  1. Stop the instance
  2. 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]
  3. Start the instance
  4. Access with root user (mysql -uroot -hlocalhost); 
  5. 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’;”

  6. Stop the instance
  7. Edit my.cnf and remove skip-grant-tables and skip-networking
  8. Start MySQL again
  9. 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

I’m trying to install queXS cati app on my Ubuntu desktop and I installed MySQL server and PHP 5 and I cannot login into MySQL server as root without password:

mysql -u root 

it says

ERROR 1045(28000) : Access denied for user 'root@localhost' (using password: no )

But it’s okay when I enter mysql -u root -p

I can’t figure out what the problem is.

oerdnj's user avatar

oerdnj

7,88038 silver badges49 bronze badges

asked Jan 7, 2014 at 10:42

user232705's user avatar

1

Add switch -p for password based login:

mysql -u root -p

That is the normal behaviour. You set a root password for your database so from now on you can’t access it without password. That is why it reports:

Access denied for user ‘root@localhost’ (using password: no )

Obviously when you give the password with the -p switch you succeed.

pocket-full-of-quarters's user avatar

answered Jan 7, 2014 at 10:47

falconer's user avatar

falconerfalconer

14.7k3 gold badges45 silver badges66 bronze badges

In simple words your «root» session does not know the password of the mysql root user.

If you want to make it easier to access your mysql, create a file .my.cnf in /root/ with these lines:

[mysqladmin]
 user = root
 password = mysqlrootpassword
[mysql]
 user = root
 password = mysqlrootpassword
[mysqldump]
 user = root
 password = mysqlrootpassword

where of course mysqlrootpassword is your password for mysql’s root password. When you execute mysql it uses this password.

Attend to the safety of this file — give it secure rights, so that nobody on your server can read it!

Zanna's user avatar

Zanna

68.3k55 gold badges210 silver badges320 bronze badges

answered Jan 16, 2014 at 22:25

pl_'s user avatar

2

Login to webmin and under servers, access the mySQLdatabase server.You will then be able to set the (user) password provided you have:

mysql -u (**user**) -p < /usr/share/doc/rsyslog-mysql-5.8.10/createDB.sql.

The web gui is easy but to be secure use the terminal.

cheers.

Charles Green's user avatar

answered Sep 24, 2014 at 12:36

SLAYER_FIFA15's user avatar

1

I just installed a fresh copy of Ubuntu 10.04.2 LTS on a new machine. I logged into MySQL as root:

david@server1:~$ mysql -u root -p123

I created a new user called repl. I left host blank, so the new user can may have access from any location.

mysql> CREATE USER 'repl' IDENTIFIED BY '123';
Query OK, 0 rows affected (0.00 sec)

I checked the user table to verify the new user repl was properly created.

mysql> select host, user, password from mysql.user;
+-----------+------------------+-------------------------------------------+
| host      | user             | password                                  |
+-----------+------------------+-------------------------------------------+
| localhost | root             | *23AE809DDACAF96AF0FD78ED04B6A265E05AA257 |
| server1   | root             | *23AE809DDACAF96AF0FD78ED04B6A265E05AA257 |
| 127.0.0.1 | root             | *23AE809DDACAF96AF0FD78ED04B6A265E05AA257 |
| ::1       | root             | *23AE809DDACAF96AF0FD78ED04B6A265E05AA257 |
| localhost |                  |                                           |
| server1   |                  |                                           |
| localhost | debian-sys-maint | *27F00A6BAAE5070BCEF92DF91805028725C30188 |
| %         | repl             | *23AE809DDACAF96AF0FD78ED04B6A265E05AA257 |
+-----------+------------------+-------------------------------------------+
8 rows in set (0.00 sec)

I then exit, try to login as user repl, but access is denied.

david@server1:~$ mysql -u repl -p123
ERROR 1045 (28000): Access denied for user 'repl'@'localhost' (using password: YES)
david@server1:~$ mysql -urepl -p123
ERROR 1045 (28000): Access denied for user 'repl'@'localhost' (using password: YES)
david@server1:~$ 

Why is access denied?

culix's user avatar

asked Mar 28, 2013 at 19:44

davidjhp's user avatar

1

The reason you could not login as repl@'%' has to do with MySQL’s user authentication protocol. It does not cover patterns of users as one would believe.

Look at how you tried to logged in

mysql -u repl -p123

Since you did not specify an IP address, mysql assumes host is localhost and tries to connect via the socket file. This is why the error message says Access denied for user 'repl'@'localhost' (using password: YES).

One would think repl@'%' would allow repl@localhost. According to how MySQL perform user authentication, that will simply never happen. Would doing this help ?

mysql -u repl -p123 -h127.0.0.1

Believe it or not, mysql would attempt repl@localhost again. Why? The mysql client sees 127.0.0.1 and tries the socket file again.

Try it like this:

mysql -u repl -p123 -h127.0.0.1 --protocol=tcp

This would force the mysql client to user the TCP/IP protocol explicitly. It would then have no choice but to user repl@'%'.

Community's user avatar

answered Mar 28, 2013 at 20:40

RolandoMySQLDBA's user avatar

RolandoMySQLDBARolandoMySQLDBA

177k32 gold badges308 silver badges506 bronze badges

0

You should issue for localhost specific to it.

  GRANT USAGE ON *.* TO 'repl'@'localhost' IDENTIFIED BY '123';

And try connecting.

answered Mar 29, 2013 at 5:40

Mannoj's user avatar

MannojMannoj

1,4992 gold badges14 silver badges34 bronze badges

The problem is these two accounts, added by default.

http://dev.mysql.com/doc/refman/5.5/en/default-privileges.html

+-----------+------------------+-------------------------------------------+
| host      | user             | password                                  |
+-----------+------------------+-------------------------------------------+
| localhost |                  |                                           |
| server1   |                  |                                           |
+-----------+------------------+-------------------------------------------+

A blank user name is a wildcard, so no matter what account you use, it matches this user if MySQL thinks you’re connecting from localhost or your local server name (server1 in this case)… since they have no password, any password you try is wrong. User authentication only tries the first match, so the user you created never gets noticed when your host is localhost (or your server name).

Delete these two from the mysql.user table and then FLUSH PRIVILEGES;.

Or, the mysql_secure_installation script can do this for you, although I tend to prefer doing things manually.

http://dev.mysql.com/doc/refman/5.5/en/mysql-secure-installation.html

answered Mar 30, 2013 at 2:02

Michael - sqlbot's user avatar

Michael — sqlbotMichael — sqlbot

22.3k2 gold badges46 silver badges75 bronze badges

Database may not be configured yet just issue a no-arg call:

mysql <enter>

Server version: xxx

Copyright (c) xxx

Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.

Mysql [(none)]> 

If Mysql must be set a root password, you can use

mysql_secure_installation

answered Apr 18, 2020 at 7:45

TRicks43's user avatar

Make sure that all fields in the connector are set up with the correct details

host = «localhost»,
user = «CorrectUser»,
passwd = «coRrectPasswd»,
database = «CorreCTDB»

Check for upper and lowercase errors as well — 1045 is not a Syntax error, but has to do with incorrect details in the connector

answered Dec 13, 2019 at 22:59

Johan Swan's user avatar

This could be an issue with corruption of your mysql database. Tables inside mysql database like user table can get corrupt and may cause issued.

Please do a check on those

myisamchk /var/lib/mysql/mysql/ *.MYI

Usually while checking or fixing myisam tables we would like to take mysql down first. If this problem is still not solve please try this out aswell.

If they are corrupt then you can fix them using

myisamchk —silent —force —fast /path/table-name.MYI

Thanks,

Masood

answered Mar 31, 2013 at 17:25

Masood Alam's user avatar

grep 'temporary password' /var/log/mysqld.log
Sort date (newest date)

You may see something like this;

[root@SERVER ~]# grep 'temporary password' /var/log/mysqld.log
2016-01-16T18:07:29.688164Z 1 [Note] A temporary password is generated for root@localhost: O,k5.marHfFu
2016-01-22T13:14:17.974391Z 1 [Note] A temporary password is generated for root@localhost: b5nvIu!jh6ql
2016-01-22T15:35:48.496812Z 1 [Note] A temporary password is generated for root@localhost: (B*=T!uWJ7ws
2016-01-22T15:52:21.088610Z 1 [Note] A temporary password is generated for root@localhost: %tJXK7sytMJV
2016-01-22T16:24:41.384205Z 1 [Note] A temporary password is generated for root@localhost: lslQDvgwr3/S
2016-01-22T22:11:24.772275Z 1 [Note] A temporary password is generated for root@localhost: S4u+J,Rce_0t
[root@SERVER ~]# mysql_secure_installation

Securing the MySQL server deployment.

Enter password for user root: 

The existing password for the user account root has expired. Please set a new password.

New password: 

Re-enter new password:

If you see it says

... Failed! Error: Your password does not satisfy the current policy requirements
That means your password needs to have a character such as ! . # - etc...
mix characters well, upper case, lower case, ! . , # etc...

New password: 

Re-enter new password: 
The 'validate_password' plugin is installed on the server.
The subsequent steps will run with the existing configuration
of the plugin.
Using existing password for root.

Estimated strength of the password: 100 
Change the password for root ? ((Press y|Y for Yes, any other key for No) : Y

New password: 

Re-enter new password: 

Estimated strength of the password: 100 
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : Y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : Y
Success.


Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : Y
Success.

By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


Remove test database and access to it? (Press y|Y for Yes, any other key for No) : Y
 - Dropping test database...
Success.

 - Removing privileges on test database...
Success.

Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : Y
Success.

All done! 
[root@SERVER ~]# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 11
Server version: 5.7.10 MySQL Community Server (GPL)

Watch the last 10 minutes of this video, it teaches you how you do it.

This “access denied” error is one of the most common errors you’ll get when working with MySQL.

Learn how to fix it, and see a range of solutions if the suggested fix does not work, in this article.

When you try to connect to a MySQL database on your own computer (called “localhost”), you may get this error:

Access denied for user 'root'@'localhost' (using password: YES)

You might get an error code in front of it:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

You might also get the error with “using password no”:

Access denied for user 'root'@'localhost' (using password: NO)

You’ll see this if you log into MySQL using the command line:

mysql -u root -p

You might also see this if you log in to MySQL using an IDE such as MySQL Workbench. Or even if you use phpMyAdmin.

What does this mean? How can you fix it?

There are a few solutions to this, which I’ve detailed below. Try one, and if it doesn’t work, try another one.

Also a tip for logging in: don’t enter your password in the command line itself, because this will be stored in your command history. Use the -p option, as mentioned above, and then you’ll be prompted to enter the password.

Solution 1: Sudo then Change Password

If you get the “access denied” error, one way to solve it is by using sudo to log in to mysql and change the root password.

Step 1: Open the command line on your system.

Step 2: Open mysql using the sudo command:

sudo mysql

Step 3: Enter the password for this account.

Step 4: Change the auth_plugin to mysql_native_password, and the password for the root account, in a single command:

ALTER USER 'root'@'localhost'
IDENTIFIED WITH mysql_native_password BY 'your_new_password';

Substitute the word your_new_password with a new secure password that you want to use for the root account.

The mysql_native_password method is a traditional method of authentication and will allow you to login.

Step 5: Flush the privileges, which tells the server to refresh the grant tables and apply your changes, with this command:

FLUSH PRIVILEGES;

Step 6: You can confirm that the new authentication method, or plugin, is used by selecting from the mysql.user table.

SELECT user, plugin
FROM mysql.user

Results:

user plugin
root mysql_native_password

Step 7: Exit the console by pressing CTRL + D or typing exit.

exit;

Step 8: Log in to mysql using the root account and the new password you set, which should work:

mysql -u root -p

You should now be logged in to the root account in mysql.

Solution 2: Edit My.cnf File

If the above solution did not work, you may need to edit the mysql.cnf file to allow for changes to the root account.

Step 1: Open the my.cnf file. This may be stored in:

/etc/my.cnf
/etc/mysql/my.cnf

If you’re not sure where it is, search your MySQL installation folder (e.g. on Windows or Mac) for the file.

If you don’t have a my.cnf file (MacOS does not include one by default). You can create one in the /etc folder if you like.

Step 2: Add the word skip-grant-tables under the word [mysqld]. Your file may look like this:

[mysqld]
skip-grant-tables

Step 3: Restart the MySQL server.

Step 4: Login to the root account:

mysql -u root -p

Step 5: Flush the privileges, which tells the server to refresh the grant tables and apply your changes, with this command:

FLUSH PRIVILEGES;

Step 6: Set a new password for the account:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'your_new_password';

Substitute the word your_new_password with a new secure password that you want to use for the root account.

Step 7: Open the my.cnf file you opened in step 1, and remove the line about skip-grant-tables, and save the file.

Step 8: Restart the MySQL server again.

Step 9: Log in to the root account again:

mysql -u root -p

You should now be able to log in successfully with your new password and not get an error.

Conclusion

Either of these two solutions should hopefully solve the problem for you, and you should no longer get the error “Access denied for user ‘root’@’localhost’”.

If you have any questions, feel free to use the comments section below.

Like this post? Please share to your friends:
  • N700e ошибка e34
  • Mysql error 1043 08s01 bad handshake
  • Mysqldump log error
  • Mysql create trigger syntax error
  • Mysqldump got error 2002