Error 1045 28000 access denied for user root localhost using password no freebsd

This error is making me crazy: # mysql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) I'm trying to configure a fresh install of mysql-5.7.10. I cannot access the server to explore the database table contents, etc. Seems like a Catch22. I've copied the...

  • #1

This error is making me crazy:

Code:

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

I’m trying to configure a fresh install of mysql-5.7.10. I cannot access the server to explore the database table contents, etc. Seems like a Catch22. I’ve copied the

/usr/local/etc/my.cnf

from an adjacent working server in the rack, but same failure. Apparently the fresh installed version «thinks» that the root user has a password . . .but I have no idea what that might be. I’ve tried toggling the

to

. . .but to no avail.

Any suggestions?

  • #2

New Install?

I find it easier to just reset the root password.

Here are the steps:

Stop the server
# service mysql-server stop

Restart it with mysqld —skip-grant-tables
# mysqld --skip-grant-tables &

Login as root no password required
# mysql -u root

mysql> use mysql;

I then like to see the users I am going to be dealing with so…

mysql> select user,host from user where user='root';

Code:

+------+-----------+
| user | host      |
+------+-----------+
| root | localhost |
+------+-----------+
1 row in set (0.00 sec)

So, now I reset the password…

mysql> update user set authentication_string = password('<newPassword>) where user='root';
mysql> flush privileges;
mysql> exit

Now you can either reboot, or manually kill the mysqld processes and restart the server.

Your root password should now work.

  • Thread Starter

  • #3

Restart it with mysqld —skip-grant-tables
# mysqld —skip-grant-tables &

. . .well, that blows up,

Code:

 # /usr/local/libexec/mysqld --skip-grant-tables &
[1] 13910
root@bravo:/usr/ports/databases/mysql57-server # 2016-02-21T21:03:32.395377Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2016-02-21T21:03:32.395565Z 0 [Warning] Insecure configuration for --secure-file-priv: Current value does not restrict location of generated files. Consider setting it to a valid, non-empty path.
2016-02-21T21:03:32.395608Z 0 [Note] /usr/local/libexec/mysqld (mysqld 5.7.10) starting as process 13910 ...
2016-02-21T21:03:32.399965Z 0 [ERROR] Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root!

2016-02-21T21:03:32.400004Z 0 [ERROR] Aborting

2016-02-21T21:03:32.400019Z 0 [Note] Binlog end
2016-02-21T21:03:32.400068Z 0 [Note] /usr/local/libexec/mysqld: Shutdown complete

. . .but never-the-less,

skip-grant-tables

. . .

is

specified in the

/usr/local/etc/my.cnf

.

Attempting to use the command, # mysql -u root, fails:

Code:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

This is what I’m calling a Catch22 — I can’t get to the MySQL prompt, i.e., « mysql >«, so back to service mysql-server start(server does start) . . .the but same subsequent failure scenarios persist.

  • #4

OMG…..

My mistake

the command is mysqld_safe --skip-grant-tables;

give that one a shot.

  • #5

Hi, having the same problem here. I ran the command mysqld_safe --skip-grant-tables;, which seemed to do nothing, and I couldn’t use the console anymore. I ran mysqld_safe --skip-grant-tables &, which ran the mysql process fine, but I am still getting the same error when I run mysql -u root. Any suggestions?

SirDice


  • #6

The

—skip-grant-tables

skips the grant tables (who would have guessed that?). By skipping those tables you are effectively bypassing any and all authentication allowing anyone to login without a password.

  • Thread Starter

  • #7

Good morning everyone. I am still struggling with this configuration, and retired around 5:30 AM this morning for about four hours of well needed sleep. I’ve invested several hours reading the MySQL 5.7 Reference Manual (not the FreeBSD Handbook or MAN pages) regarding Server Configuration Defaults, . . . 14.3.1 InnoDB Initialization and Startup Configuration, and other sections, etc. Quite a lot to learn . . .coming from v5.6. I’ve actually de/re installed several times and have some nuances to share, and I’ll come back and edit this post after I’ve had a first cup of coffee ;)

Please standby.

Hi, having the same problem here. I ran the command mysqld_safe --skip-grant-tables;, which seemed to do nothing, and I couldn’t use the console anymore. I ran mysqld_safe --skip-grant-tables &, which ran the mysql process fine, but I am still getting the same error when I run mysql -u root. Any suggestions?

. . .and yes, permanent

—skip-grant-tables

is not a desirable «solution», but to date, has not worked for me either.

The

—skip-grant-tables

skips the grant tables (who would have guessed that?). By skipping those tables you are effectively bypassing any and all authentication allowing anyone to login without a password.

*** EDIT ***

Apologies for the delay. I’ve been at this all day, but I have resolved many problems. Getting the InnoDB engine to work has become a real «bear». I have discovered several breaks in the install scripts, the

*/my.cnf

,

/etc/rc.conf

and the

rc.d/mysql-server

bash script. Short note . . .don’t depend of the default «configurations»; plain vanilla installation is probably not going to work. I’ve got several pages of documented notes that I need to review and edit. I’ll probably post in an uploaded PDF.

  • #8

Since MySQL 5.7 a temporary password is created for the root@localhost account. This can be seen when one runs `mysqld —initialize` as per MySQL manual, with the flags from the rc script:

sudo /usr/local/libexec/mysqld --defaults-extra-file=/usr/local/etc/mysql/my.cnf --basedir=/usr/local --datadir=/var/db/mysql --user=mysql --initialize
Output:

Code:

 100
 100 200
 100 200
2016-08-23T09:40:17.766421Z 0 [Warning] InnoDB: New log files created, LSN=45790
 100
2016-08-23T09:40:18.203159Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
mysqld: Error on delete of './auto.cnf' (Errcode: 2 - No such file or directory)
2016-08-23T09:40:18.484358Z 0 [Warning] World-writable config file './auto.cnf' has been removed.

2016-08-23T09:40:18.484430Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 9a4557d3-6915-11e6-9568-001f29048cd2.
2016-08-23T09:40:18.493060Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2016-08-23T09:40:18.774004Z 0 [Warning] CA certificate ca.pem is self signed.
2016-08-23T09:40:18.925572Z 1 [Note] A temporary password is generated for root@localhost: ,BsPikk5has.

The rc script a) uses the deprecated mysql_install_db and b) doesn’t echo the temporary password, but suppresses all output. The following patch fixes the issue:

Code:

diff -ur /usr/local/etc/rc.d.orig/mysql-server /usr/local/etc/rc.d/mysql-server
--- /usr/local/etc/rc.d.orig/mysql-server  2016-08-22 10:06:21.000000000 +0000
+++ /usr/local/etc/rc.d/mysql-server  2016-08-23 16:17:54.364601968 +0000
@@ -52,12 +52,17 @@
 procname="/usr/local/libexec/mysqld"
 start_precmd="${name}_prestart"
 start_postcmd="${name}_poststart"
-mysql_install_db="/usr/local/bin/mysql_install_db"
-mysql_install_db_args="--defaults-extra-file=${mysql_optfile} --basedir=/usr/local --datadir=${mysql_dbdir} --mysqld-file=${procname} --user=${mysql_user}"
+mysql_install_db="${procname}"
+# NOTE: --initialize MUST be at the end or other options will be
+# "unknown variables" and initialization fails.
+# This is why it's set hardcoded in mysql_create_auth_tables rather then the
+# options variable here.
+mysql_install_db_args="--defaults-extra-file=${mysql_optfile} --basedir=/usr/local --datadir=${mysql_dbdir} --user=${mysql_user}"

 mysql_create_auth_tables()
 {
-  eval $mysql_install_db $mysql_install_db_args >/dev/null 2>/dev/null
+  $mysql_install_db $mysql_install_db_args --initialize 2>&1 | 
+  /usr/bin/sed -ne '/A temporary password is generated/ s/^.*Note] //p'
 }

 mysql_prestart()

SirDice


  • #9

Please submit those patches so the port can be adjusted.

I’ve tried multiple solutions from StackOverflow but haven’t had any success. I’m on Mac OSX (Sierra 10.12.3) trying to create a new database and user. From terminal I enter:

mysql -u root

which outputs this error:

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

To try and resolve it I stopped mysql from ‘System Preferences’, then from terminal typed:

sudo mysqld_safe —skip-grant-tables

I opened a second tab and entered:

mysql -u root

Then from in mysql:

update mysql.user set password_expired = 'N', authentication_string=PASSWORD('newpassword') where user = 'root';

flush privileges;

I then restart the computer (killing the process with CMD + C doesn’t work). After restarting, trying mysql -u root still produces the same error.

I am able to access mysql via a MySQL client and a non-root user.

Any help is appreciated.

asked Mar 11, 2017 at 23:52

Alan P.'s user avatar

19

For security reason mysql -u root wont work untill you pass -p in command so try with below way

 mysql -u root -p[Enter]
 //enter your localhost password

answered Mar 21, 2017 at 3:59

Pramod Patil's user avatar

Pramod PatilPramod Patil

2,6542 gold badges13 silver badges20 bronze badges

1

mysql -u root -p;

And mysql will ask for the password

answered Mar 20, 2017 at 9:18

gud3's user avatar

gud3gud3

5453 silver badges10 bronze badges

2

Just to confirm: You are sure you are running MySQL 5.7, and not MySQL 5.6 or earlier version. And the plugin column contains «mysql_native_password». (Before MySQL 5.7, the password hash was stored in a column named password. Starting in MySQL 5.7, the password column is removed, and the password has is stored in the authentication_string column.) And you’ve also verified the contents of authentication string matches the return from PASSWORD(‘mysecret’). Also, is there a reason we are using DML against the mysql.user table instead of using the SET PASSWORD FOR syntax?
– spencer7593

So Basically Just make sure that the Plugin Column contains «mysql_native_password».

Not my work but I read comments and noticed that this was stated as the answer but was not posted as a possible answer yet.

answered Mar 21, 2017 at 22:51

Ansel Faillace's user avatar

Ansel FaillaceAnsel Faillace

4091 gold badge4 silver badges11 bronze badges

just use:

$ sudo mysql

without the «-u root» parameter.

answered Mar 18, 2017 at 18:43

Alex Angelico's user avatar

Alex AngelicoAlex Angelico

3,5248 gold badges30 silver badges48 bronze badges

1

If you need to skip the password prompt for some reason, you can input the password in the command (Dangerous)

mysql -u root --password=secret

answered Mar 21, 2017 at 19:53

lofihelsinki's user avatar

lofihelsinkilofihelsinki

2,4602 gold badges22 silver badges35 bronze badges

You must run your mysql by xampp-controle.exe in folder XAMPP. After that login:

mysql -u root

answered Mar 18, 2017 at 18:38

b2ok's user avatar

b2okb2ok

5506 silver badges13 bronze badges

5

Is it possible the root password is not what you think it is? Have you checked the file /root/.mysql_secret for the password? That is the default location for the automated root password that is generated from starting from version 5.7.

cat /root/.mysql_secret

answered Mar 21, 2017 at 19:05

invalid entry's user avatar

Try this (on Windows, i don’t know how in others), if you have changed password a now don’t work.

1) kill mysql
2) back up /mysql/data folder
3) go to folder /mysql/backup
4) copy files from /mysql/backup/mysql folder to /mysql/data/mysql (rewrite)
5) run mysql

In my XAMPP on Win7 it works.

answered Sep 15, 2017 at 13:20

daewoo's user avatar

Comment by @Niagaradad helped me. I was entering the wrong password the whole time.

Notice the error message

ERROR 1045 (28000): Access denied for user ‘ayaz’@’localhost’ (using password: YES)

It says, Password: Yes. That means I am sending the password to SQL and that is wrong.

Usually root account doesn’t have password if you haven’t set one. If you have installed mysql via homebrew then root account won’t have a password.

Here is the comment.

so, not exactly the same then. NO means you are not sending a password to MySQL. YES means you are sending a password to MySQL but the incorrect one. Did you specifically set a password for the mysql root user when you installed MySQL? By default there is no password so you can use mysql -u root -p and hit enter.

answered Nov 26, 2019 at 10:11

mohammed_ayaz's user avatar

In my case, I needed to Edit Inbound Rules on my AWS RDS instance to accept All Traffic. The default TCP/IP constraint prevented me from creating a database from my local machine otherwise.

answered Feb 9, 2021 at 4:31

Pigpocket's user avatar

PigpocketPigpocket

4295 silver badges21 bronze badges

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.

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

Порядок действий для установки/смены пароля 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» означает лишь, что пароль и не использовался.

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.

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

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 badges307 silver badges505 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.2k2 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

Понравилась статья? Поделить с друзьями:
  • Error 1045 28000 access denied for user root localhost using password no debian
  • Error 1045 28000 access denied for user odbc localhost using password yes
  • Error 1045 28000 access denied for user debian sys maint localhost using password yes
  • Error 1045 28000 access denied for user administrator localhost using password no
  • Error 1045 28000 access denied for user admin localhost using password no