Using password no mysql ошибка

I’m trying to run WordPress in my Windows desktop and it needs MySQL.

I install everything with Web Platform Installer which is provided by Microsoft. I never set a root password for MySQL and in the final step of installing WordPress, it asks for a MySQL server password.

What is the default password for root (if there is one) and how to change it?

I tried:

mysql -u root password '123'

But it shows me:

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

After this I try:

mysql -u root -p

However, it asks for a password which I don’t have.


Update: as Bozho suggested, I did the following:

  1. I stopped the MySQL Service from Windows services

  2. Opened CMD

  3. Changed the location to c:program filesmysqlbin

  4. Executed the command below

    mysqld --defaults-file="C:\program files\mysql\mysql server 5.1\my.ini" --init-files=C:\root.txt

  5. The command ran with a warning about character set which I mentioned below

  6. I start the MySQL service from Windows services

  7. I write in the command line

    mysql -u root -p
    EnterPassword: 123 // 123 was the password

  8. The command line shows the following error

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

How do I solve this?

starball's user avatar

starball

15.1k6 gold badges28 silver badges134 bronze badges

asked Jun 8, 2010 at 5:53

Nasser Hadjloo's user avatar

Nasser HadjlooNasser Hadjloo

12.2k15 gold badges69 silver badges100 bronze badges

4

for this kind of error; you just have to set new password to the root user as an admin. follow the steps as follows:

[root ~]# mysql -u root
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password:NO)
  1. Stop the service/daemon of mysql running

     [root ~]# service mysql stop   
     mysql stop/waiting
    
  2. Start mysql without any privileges using the following option;
    This option is used to boot up and do not use the privilege system of MySQL.

     [root ~]# mysqld_safe --skip-grant-tables &
    

At this moment, the terminal will seem to halt. Let that be, and use new terminal for next steps.

  1. enter the mysql command prompt

     [root ~]# mysql -u root
     mysql> 
    
  2. Fix the permission setting of the root user ;

     mysql> use mysql;
     Database changed
     mysql> select * from  user;
     Empty set (0.00 sec)
     mysql> truncate table user;
     Query OK, 0 rows affected (0.00 sec)
     mysql> flush privileges;
     Query OK, 0 rows affected (0.01 sec)
     mysql> grant all privileges on *.* to root@localhost identified by 'YourNewPassword' with grant option;
     Query OK, 0 rows affected (0.01 sec)
    

*if you don`t want any password or rather an empty password

    mysql> grant all privileges on *.* to root@localhost identified by '' with grant option;
    Query OK, 0 rows affected (0.01 sec)*
    mysql> flush privileges;
    Query OK, 0 rows affected (0.00 sec)

Confirm the results:

    mysql> select host, user from user;
+-----------+------+
| host      | user |
+-----------+------+
| localhost | root |
+-----------+------+
1 row in set (0.00 sec)
  1. Exit the shell and restart mysql in normal mode.

     mysql> quit;
     [root ~]# kill -KILL [PID of mysqld_safe]
     [root ~]# kill -KILL [PID of mysqld]
     [root ~]# service mysql start
    
  2. Now you can successfully login as root user with the password you set

      [root ~]# mysql -u root -pYourNewPassword 
      mysql> 
    

Ryan M - Regenerate response's user avatar

answered May 29, 2014 at 2:37

user2977819's user avatar

8

You can reset your root password. Have in mind that it is not advisable to use root without password.

answered Jun 8, 2010 at 5:54

Bozho's user avatar

BozhoBozho

586k144 gold badges1057 silver badges1137 bronze badges

4

1) You can set root password by invoking MySQL console. It is located in

C:wampbinmysqlmysql5.1.53bin by default.

Get to the directory and type MySQL. then set the password as follows..

    > SET PASSWORD FOR root@localhost = PASSWORD('new-password');

2) You can configure wamp’s phpmyadmin application for root user by editing

C:wampappsphpmyadmin3.3.9config.inc.php 

Note :- if you are using xampp then , file will be located at

C:xamppphpMyadminconfig.inc.php

It looks like this:

        $cfg['Servers'][$i]['verbose'] = 'localhost';
        $cfg['Servers'][$i]['host'] = 'localhost';
        $cfg['Servers'][$i]['port'] = '';
        $cfg['Servers'][$i]['socket'] = '';
        $cfg['Servers'][$i]['connect_type'] = 'tcp';
        $cfg['Servers'][$i]['extension'] = 'mysqli';
        $cfg['Servers'][$i]['auth_type'] = 'config';
        $cfg['Servers'][$i]['user'] = 'root';
        $cfg['Servers'][$i]['password'] = 'YOURPASSWORD';
        $cfg['Servers'][$i]['AllowNoPassword'] = false;

The error «Access denied for user ‘root@localhost’ (using password:NO)»
will be resolved when you set $cfg['Servers'][$i]['AllowNoPassword'] to false

If you priviously changed the password for ‘root@localhost’, then you have to do 2 things to solve the error «Access denided for user ‘root@localhost'»:

  1. if [‘password’] have a empty quotes like ‘ ‘ then put your password between quotes.
  2. change the (using password:NO) to (using password:YES)

This will resolve the error.

Note: phpmyadmin is a separate tool which comes with wamp.
It just provide a interface to MySQL. if you change my sql root’s password, then you should change the phpmyadmin configurations. Usually phpmyadmin is configured to root user.

Andreas's user avatar

Andreas

6,4452 gold badges34 silver badges46 bronze badges

answered Dec 25, 2012 at 8:35

yellobird's user avatar

yellobirdyellobird

2793 silver badges3 bronze badges

2

Use mysql -u root -p
It will ask for password, insert password and enter.

answered May 16, 2019 at 11:10

Vikash Kumar's user avatar

2

I was getting the same error on OS X El captain.
Mysql version 5.7 . I was able to connect to mysql with root after executing these steps.

Stop the mysql server

sudo mysql.server stop

Start mysql in safe mode

sudo mysqld_safe --skip-grant-tables

Using mysqld, Change the database to mysql and update the details for user ‘root’.

show databases;
use mysql;
UPDATE mysql.user 
    SET authentication_string = PASSWORD('MyNewPass'), password_expired = 'N'
    WHERE User = 'root' AND Host = 'localhost';
exit;

After that kill the ‘mysqld_safe’ process and start mysql normally. You should be able to login to mysql using root and new password. SQL docs for more details

answered Jul 5, 2016 at 10:54

Sushantkumar M's user avatar

Simply edit my.ini file in C:xamppmysqlbin path. Just add:

skip-grant-tables

line in between lines of # The MySQL server [mysqld] and port=3306. Then restart the MySQL server.

Looks like:

Screenshot

Stephen Rauch's user avatar

Stephen Rauch

47.5k31 gold badges106 silver badges135 bronze badges

answered Mar 16, 2018 at 0:19

Ryan Oscar's user avatar

Ryan OscarRyan Oscar

2791 gold badge4 silver badges19 bronze badges

1

For some information I’ve get error after changing password:

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

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

In both cases there was error.

But the thing is after that I’ve tried it with

mysql -uroot -ppassword instead of

mysql -u root -p password -> with spaces between -uroot and -ppassword so maybe if someone get trouble can try this way.

Community's user avatar

answered Mar 1, 2020 at 18:39

profiile_samir's user avatar

Make sure the MySQL service is running on your machine, then follow the instructions from MySQL for initially setting up root (search for ‘windows’ and it will take you to the steps for setting up root):

Securing the Initial MySQL Account

Kuro Neko's user avatar

answered Jun 8, 2010 at 5:56

sholsapp's user avatar

sholsappsholsapp

15.4k10 gold badges49 silver badges66 bronze badges

3

Another solution if someone gets the error The specified password for user account ‘root’ is not valid, or failed to connect to the database server also with the right password, is the follow

•In the Windows registry, delete the mysql_pwd reg key under HKCUSoftwareMicrosoftWebPlatformInstaller

•Unistall older version of MySQL .NET connector

•Download and install the latest MySql .NET Connector.

answered Apr 5, 2014 at 18:50

Silverstorm's user avatar

SilverstormSilverstorm

15.2k2 gold badges38 silver badges52 bronze badges

1

  1. Change the password from config.inc.php present in C:xamppphpMyAdmin.
  2. Type mysql -u root -p in the command prompt.
  3. You will be asked to enter the password. Enter that password which you updated in the config.inc.php.

double-beep's user avatar

double-beep

4,97617 gold badges32 silver badges41 bronze badges

answered May 19, 2020 at 15:39

user12682744's user avatar

1

In your code replace the ‘root’ with your Server username and password with your server password.
For example if you have DB and your php files on the server http://www.example.com
then obviously you would have to enter into this server site using your username and password.

answered Jun 22, 2015 at 19:21

Pir Fahim Shah's user avatar

Pir Fahim ShahPir Fahim Shah

10.4k1 gold badge79 silver badges80 bronze badges

For MySQL 5.7. These are the below steps:

Stop your MySQL server completely. This can be done by accessing the Services window inside Windows XP and Windows Server 2003, where you can stop the MySQL service.

Open your MS-DOS command prompt using «cmd» inside the Run window. Inside it navigate to your MySQL bin folder, such as C:MySQLbin using the cd command.

Execute the following command in the command prompt: mysqld.exe -u root —skip-grant-tables

Leave the current MS-DOS command prompt as it is, and open a new MS-DOS command prompt window.

Navigate to your MySQL bin folder, such as C:MySQLbin using the cd command.

Enter mysql and press enter.

You should now have the MySQL command prompt working. Type use mysql; so that we switch to the «mysql» database.

Execute the following command to update the password:

update user set authentication_string=password(‘1111′) where user=’root’;

answered Dec 1, 2016 at 2:30

Katie's user avatar

KatieKatie

4527 silver badges18 bronze badges

0

Some times it just happens due to installation of Wamp or changing of password options of root user.
One can use privilages—>root (user) and then set password option to NO to run the things without any password OR set the password and use it in the application.

Pieter Goosen's user avatar

answered Feb 5, 2015 at 8:07

Sayyad's user avatar

If you are using XAMPP just go to C:xamppphpMyAdmin and then open config.inc.php find $cfg['Servers'][$i]['password'] = '' line and put your password there.

answered Aug 4, 2018 at 6:22

Ajay Rawat's user avatar

Ajay RawatAjay Rawat

3073 silver badges10 bronze badges

if you changed the port to non standard one, then you need to specify it:

$connection = mysqli_connect('localhost:3308', 'root', '', 'loginapp');

Kuro Neko's user avatar

answered May 21, 2020 at 18:54

Mitchell Yuen's user avatar

It happens because of the security reason.

try with the following

mysql -u root -p    

click enter and enter the password and try again

answered Apr 27, 2021 at 8:30

janadari ekanayaka's user avatar

0

If the root account exists but has no password, connect to the server as root using no password, then assign a password. This was my situation when I encountered this issue.

Connect to the server as root using no password:

$> mysql -u root --skip-password

Assign a password:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'root-password';

I was able to solve my problem this way. Hope this helps someone who encounters a similar issue in the future. Cheers!

Reference: https://dev.mysql.com/doc/refman/8.0/en/default-privileges.html

answered Jan 9, 2022 at 17:10

K M Rakibul Islam's user avatar

K M Rakibul IslamK M Rakibul Islam

33.6k12 gold badges89 silver badges110 bronze badges

This means that the user has no access. This can be fixed in the following ways

make sure the host is set to ´%´

 insert into mysql.user (Host, User, Password) VALUES ('%', 'root', password('setyourpasswordhere'));
    GRANT ALL ON *.* TO 'root'@'%' WITH GRANT OPTION;

or if you are using SQL workbench, you can create an user under

Adminstration --> users and previlages --> click on Add account button and create a new user, with hosts as **%** and grant the previlages in Adminstrative roles, schema previalges tabs.

enter image description here

answered Mar 10 at 10:36

Ramya Musunuru's user avatar

mysqladmin -u root -p password

enter your current password

then

enter your new password

0bserver07's user avatar

0bserver07

3,3701 gold badge28 silver badges56 bronze badges

answered Oct 7, 2013 at 16:26

djrconcepts's user avatar

djrconceptsdjrconcepts

6255 silver badges6 bronze badges

2

Ошибка: Access denied for user ‘root’@’localhost’ (Using password: YES и NO)

При работе с системой MySQL могут возникнуть самые разные ошибки, и на этапе освоения программы разобраться с ними может быть сложно. Одна из наиболее распространенных проблем — ошибка 1045, которая сопровождается сообщением Access denied for user ‘root’@’localhost’ (Using password: YES и NO). Сегодня я расскажу, как ее исправить.

Понять суть проблемы можно, переведя сообщение об ошибке на русский язык. Означает оно, что пользователю с именем root на машине localhost запрещен доступ к БД при использовании пароля или без него.

Окно Connection Error

Причины ошибки Access denied for user ‘root’@’localhost’

Чтобы свободно получить доступ в MySQL, должно совпасть три параметра, описывающих пользователя базы данных — имя, название машины и пароль. Если есть какие-то несовпадения, доступ будет запрещен. Самая простая причина проблемы — неправильный ввод пароля. Кроме этого, вызывать ошибку может неправильный синтаксис.

В системе MySQL нет простой зависимости имя пользователя – пароль, название хоста играет важную роль в получении доступа к БД. Оно может иметь вид IP-адреса, доменного имени, ключевого слова (например, localhost) или символа, объединяющего несколько машин в группу (например, % — любой хост, кроме локального).

Ошибка Access denied

Наиболее распространенные ошибки при обращении к БД:

  1. При присвоении прав новому пользователю не был указан адрес машины, с которой он может подключаться. В таком случае ему автоматически будет разрешено пользоваться БД с любого хоста, кроме локального, и при попытке подключения с localhost возникнет ошибка доступа.
  2. Неправильно расставленные кавычки. Если при создании пользователя написать ‘username@localhost’, это будет значить, что username@localhost может подключаться с любой машины, кроме локальной, а не что username может подключаться с компьютера localhost. Логин пользователя и имя машины должны иметь свою пару кавычек.
  3. Использование пароля при его отсутствии в базе данных.

В зависимости от того, при каком способе подключения к БД возникает ошибка Access denied for user ‘root’@’localhost’ (Using password: YES или NO), используются разные методы решения проблемы.

Если ошибка Access denied for user появляется с указанием Using password: YES, проблема заключается в неправильном вводе пароля. Проверить это можно, открыв таблицу mysql.user, в которой хранятся данные обо всех пользователях.

Таблица USE Mysql

Порядок действий таков:

  1. Откройте таблицу пользователей.
  2. Проверьте, существует ли пользователь root с хостом localhost. Если он есть, смотрите на поле «password». Если там пусто, зайти в базу можно без ввода пароля. Если там что-то есть, значит, вы вводите неправильный пароль.
  3. Смените пароль командой SET PASSWORD.
  4. Если пользователя root нет, создайте его, установите пароль и предоставьте ему права.

После этого в базу данных можно зайти. Если изменить данные не получается, следует использовать параметр —skip-grant-tables, который отменяет все настройки разрешений.

Файл конфигурации

Строки, которые нужно изменить в файле конфигурации

Если ошибка появляется с ключом (Using password: NO), нужно сделать следующее изменить файл config.inc.php, указав в нем правильные данные. Если проблема возникает при установке MySQL, нужно удалить базы данных старой версии программы или сменить пароль для доступа к ним, используя режим —skip-grant-tables.

Таким образом, ошибка Access denied for user ‘root’@’localhost’ (Using password: YES или NO) возникает при несоответствии пароля и имени пользователя и легко исправляется заменой данных для входа.

Опубликовано 06.06.2017 Обновлено 28.04.2021

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,88039 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.8k3 gold badges45 silver badges67 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.9k56 gold badges215 silver badges327 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

  • user1410

Решил, что пора изучать БД, и споткнулся, еще даже не сумев запустить БД.

В видеокурсе показано было следующее:
sudo apt-get install mysql-server
mysql -u root -p

Автор ввел пароль и спокойно зашел. Я получил ошибку, указанную в заголовке.
Начал гуглить и наткнулся примерно на следующие советы:
Совет 1: заходить через mysql -u root, то есть не добавлять -p. Не помогло, ошибка прежняя.
Совет 2: mysqladmin -u root password [newpassword]. То же самое.

Так что же делать?


  • Вопрос задан

    более трёх лет назад

  • 108763 просмотра

Пригласить эксперта

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

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


  • Показать ещё
    Загружается…

09 июн. 2023, в 01:21

10000 руб./за проект

09 июн. 2023, в 01:06

50000 руб./за проект

09 июн. 2023, в 00:36

1000 руб./за проект

Минуточку внимания

If the error persists, follow these commands:

  1. Stop the mysql daemon by typing:
mysql stop
  1. Start mysql without any privileges using:
mysqld_safe --skip-grant-tables &
  1. The terminal will stop responding. Open a new terminal and type:
mysql -u root
  1. Enter the permission setting of the root user by typing:
mysql> use mysql;

mysql> select * from user;

mysql> flush privileges;

mysql> grant all privileges on *.* to root@localhost identified by 'Password' with grant option;

Enter your password in place of Password.

  1. Exit the shell:
mysql> quit
  1. Restart mysql by typing:
kill -KILL [PID of mysqld_safe]
kill -KILL [PID of mysqld]
service mysql start
  1. Retry logging in by typing:
mysql -u root -p password

Понравилась статья? Поделить с друзьями:
  • Users usr общая файловая ошибка при доступе
  • Usergate ошибка соединения сервер недоступен 0
  • Usergate ошибка подключения к серверу
  • Usergate 10061 ошибка соединения с сервером
  • Userassembly dll genshin impact ошибка