Mysql пароль root по умолчанию windows

When installing MySQL, you may noticed that it does not ask for password. In this article, I will show on how to find MySQL default password.

When installing MySQL, you may noticed that it does not ask for a password. This become troublesome when you want to connect your application to MySQL database. In this article, I will show you on how to find MySQL default password.

Well, straight forward, by default the username is root and there is no password setup. You may need to reset the root password.

Also, in case you have accidently put a password during installation process and can’t recall the password, you need to reset the password.

There is no way to view the password as it’s already written as hashed.

How To Reset MySQL Default Password

Windows OS

1. Ensure that your logged on account has administrator rights.

2. On the windows search box, search for services.msc and click to open.

3. Scroll down to all services with its status. Find MySQL services, right-click on it and click stop services.

4. Create a text file which contains the SQL statement in a single line as below:

ALTER USER ‘root’@’localhost’ IDENTIFIED BY ‘MyNewPass’;

Change MyNewPass to your new desired password.

5. Save it to a text file. For example, save it as C:new-password.txt.

6. On the windows search box, search for cmd and click Run as administrator.

7. Start the MySQL with init_file system variable set to text file name created as below:

C:> cd “C:Program FilesMySQLMySQL Server 5.7bin”
C:> mysqld –init-file=C:\mysql-init.txt

You may replace your MySQL installation location after cd command.

Linux

1. Open terminal.

2. Stop MySQL server.

sudo service mysql stop

Or

sudo /usr/local/mysql/support-files/mysql.server stop

3. Start MySQL in safe mode.

sudo mysqld_safe –skip-grant-tables

4. Open another terminal and login as root by run below command.

mysql -u root

3. Once MySQL is logged in via terminal, run below queries.

UPDATE mysql.user SET authentication_string=PASSWORD(‘password’) WHERE User=’root’;
FLUSH PRIVILEGES;

which be looks like:

mysql>UPDATE mysql.user SET authentication_string=PASSWORD(‘password’) WHERE User=’root’;
FLUSH PRIVILEGES;

(Note: In MySQL 5.7, the password field in mysql.user table field was removed, now the field name is ‘authentication_string’.)

If you are using MySQL 5.7 and above you need to run command as below:

mysql>
use mysql;
mysql>update user set authentication_string=password(‘password’) where user=’root’;
FLUSH PRIVILEGES;

4. Now, you can exit MySQL safe mode.

mysqladmin shutdown

If you received error ‘access denied’ you can run below command with the new password:

mysqladmin -u root -p shutdown

5. Start MySQL service again by run below command.

sudo service mysql start

What If Still Failed To Reset MySQL Default Password?

If by using ALTER USER still not able to reset password, you may try to modify the user table directly by repeating the steps above and run below query:

UPDATE mysql.user
   SET authentication_string = PASSWORD(‘MyNewPass’), password_expired = ‘N’
   WHERE User = ‘root’ AND Host = ‘localhost’;
FLUSH PRIVILEGES;

Thanks for reading this article. I hope you find it helpful.

I am new to MySQL and am setting up a new instance of MySQL using the Windows Installer and am being prompted for two passwords.

The Current Root Password and the MySQL Root Password.

Is there a standard Current Root Password for new installations?

What is the difference between the two passwords.

asked Nov 26, 2013 at 16:17

Doug Kimzey's user avatar

2

If you don’t remember your current root password and want to install new instance of MySQL and you have applied other ways like "-init-file.txt", but still failed.

There is another solution which worked for me. Uninstalling MySQL from control panel didn’t remove all files, it left some references in the system.

  1. To delete MySQL files completely, open the folder path C:Usersyour pc nameAppDataRoaming and delete the MySQL folder.

  2. Then remove one more reference which is in C:ProgramDataMySQL, if not visible check your folder view options and uncheck «Don’t show hidden files».

  3. The last reference of MySQL exists in our system services:

    Type «Services» in the search box of the taskbar. Find services related to MySQL and note them down. I have two in my case(MySQLRouter and MYSQL80).

    Open the command prompt with administrator and type:

    sc delete "ServiceName",

    In my case:

    sc delete MySQL80

    sc delete MySQLRouter

    Ensure all services related to MySQL are removed by using the above command. Restart your computer and install your MySQL instance with a new configuration.

0

The standard password for user root is simply: password

Each user had its own password. So a password must belong to a user. So the only difference of password are just what they contain.

root is AFAIK the only user created upon installation. Did you create a new user after installation?

answered Nov 26, 2013 at 16:44

Mad Dog Tannen's user avatar

Mad Dog TannenMad Dog Tannen

7,0875 gold badges30 silver badges54 bronze badges

5

issue:- new mysql installation steps asks for current root password when it ideally should be prompting set new password option.

solution :-Issue could be due to existence of a previous unsuccessful mysql installation, leaving behind contents even after uninstalling.(at c:mysql,c:/ program files/mysql,c:/program data/mysql )
In my case they required manual deletion;after which new installation of mysql went on smooth .
(had to msconfig too, to handle unending windows hanging sometime during the process.)

Sunderam Dubey's user avatar

answered Jun 24, 2020 at 8:16

Sneh 's user avatar

Sneh Sneh

411 bronze badge

The community wiki has an excellent guide on the steps that one needs to follow.

Please note that uninstalling MySQL from the installer gives the option to remove all data as well, which by default is unselected.

Check the box and then uninstall MySQL.

After that, follow the guidelines in the community wiki.

answered May 13, 2020 at 11:34

Tarun Pratap's user avatar

Uninstall mysql all setup fully
Delete all files related to MySQL
From program files, program files x86:

C>username>appdata_>Roaming>mysql

After that install mysql

Walid's user avatar

Walid

7002 gold badges11 silver badges27 bronze badges

answered Jul 14, 2020 at 14:15

Shilpa Yadav's user avatar

Try switching to root user using su or sudo -i, if possible, then use password as password.

answered Jan 23, 2021 at 13:31

Hrithik Raj's user avatar

Если у вас Linux, то смотрите статью «Как сбросить пароль root для MySQL или MariaDB».

Пароль пользователя root спрашивается во время установки СУБД. Если установка делалась вручную, то есть без инстолятора, как это описано, например, в этой статье, то пароль может быть не установлен вовсе.

Если вы используете какие-то готовые сборки, которые включают в себя MySQL/MariaDB, то обратитесь за паролем на официальные сайты этих сборок. Также попробуйте такие учётные данные:

  • Пользователь: root
  • Пароль: root

Если вы действительно забыли пароль MySQL/MariaDB и вам нужно сбросить пароль root в MySQL на Windows, то данная статья расскажет, как это сделать.

Шаг 1 — Определяем версию системы управления базой данных

Найдите, в какой папке у вас расположен файл mysqld.exe. При установке по данной инструкции, этот файл расположен в папке C:Serverbinmysql-8.0bin.

Откройте командную строку. Нам понадобятся права администратора, поэтому делаем следующее: нажмите Win+x и там выберите Windows PowerShell (администратор):

Теперь перейдите в командной строке в директорию с файлом mysqld.exe, для этого используйте команду вида:

cd путьдопапки

Например, у меня это папка C:Serverbinmysql-8.0bin, тогда команда такая:

cd C:Serverbinmysql-8.0bin

Нужно определить версию MySQL/MariaDB, для этого выполните команду:

.mysql --version

Пример вывода:

C:Serverbinmysql-8.0binmysqld.exe Ver 8.0.19 for Win64 on x86_64 (MySQL Community Server - GPL)

Шаг 2 — Остановка сервера базы данных

Для изменения пароля root вы должны заранее отключить сервер базы данных. Для MySQL и MariaDB вы можете сделать это командой:

net stop mysql

После того, как сервер остановлен, вы вручную получите к нему доступ для сброса пароля рута.

Шаг 3 — Перезапуск сервера базы данных без проверки разрешений

Если вы запускаете MySQL и MariaDB без загрузки информации о привилегиях пользователя, она позволит вам без ввода пароля получить доступ к командной строке базы данных с привилегиями рута. Это позволит вам получить доступ к базе данных без знания парольной фразы. Чтобы это сделать, вам нужно не дать базе данных загрузить таблицы привилегий, которые содержат информацию о привилегиях пользователя. Поскольку это несёт риск безопасности, вы также должны избежать сетевой активности, чтобы не допустить подключения других клиентов.

Запустите базу данных без загрузки таблиц привилегий и без доступа к сети:

.mysqld --skip-grant-tables --skip-networking --shared-memory

Программа НЕ должна завершить работу, то есть теперь в это окно командной строки ничего нельзя ввести.

Шаг 4 — Смена пароля рута

Теперь вы можете подключиться к базе данных как пользователь рут, у которого не спросят пароль.

Открываем новое окно командной строки, можно без прав администратора.

Опять переходим в нужную папку

cd C:Serverbinmysql-8.0bin

И подключаемся к серверу MySQL/MariaDB

.mysql -u root

Вы сразу же увидите приглашение оболочки базы данных. Приглашение командной строки MySQL:

Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 8
Server version: 8.0.19 MySQL Community Server - GPL

Copyright (c) 2000, 2020, 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.

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

Простым способом смены пароля рута для современных версий MySQL является использование запроса ALTER USER. Тем не менее эта команда не будет работать прямо сейчас, поскольку таблицы привилегий не загружены. Давайте скажем серверу баз данных перегрузить таблицы привилегий введя команду:

FLUSH PRIVILEGES;

Теперь действительно мы можем поменять пароль рута.

Для MySQL 5.7.6 и новее, а также для MariaDB 10.1.20 и новее используйте следующую команду:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'новый_пароль';

Для MySQL 5.7.5 и старее, а также для MariaDB 10.1.20 и старее используйте:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('новый_пароль');

Не забудьте поменять новый_пароль на выбранный вами новый пароль.

Примечание: если команда ALTER USER не работает, то это обычно является признаком более серьёзной проблемы. Тем не менее вместо этой вы можете попробовать UPDATE … SET для сброса root пароля:

UPDATE mysql.user SET authentication_string = PASSWORD('новый_пароль') WHERE User = 'root' AND Host = 'localhost';

После этого не забудьте перегрузить таблицы привилегий:

FLUSH PRIVILEGES;

В любом случае вы должны видеть подтверждение, что команда успешно выполнена. Вывод:

Query OK, 0 rows affected (0.02 sec)

Выходим из сессии:

exit;

Пароль изменён, вы можете остановить запущенный вручную экземпляр сервера базы данных и перезапустить его как это было раньше.

Шаг 5 — Обычный перезапуск сервера базы данных

Для начала, остановите экземпляр сервера базы данных, который вы запустили вручную на Шаге 3. Для этого перейдите в окно с запущенной mysqld и нажмите Ctrl+c.

Затем перезапустите сервис обычным образом:

net start mysql

Теперь вы можете подтвердить, что новый пароль работает, запустите:

.mysql -u root -p

Эта команда должна вызвать приглашение в который нужно ввести новый пароль. Введите его, вы должны получить доступ к интерфейсу командной строки базы данных, как это обычно и происходит.

Заключение

Теперь вы восстановили административный доступ к серверу MySQL или MariaDB. Убедитесь, что новый пароль рута, который вы выбрали, безопасный и храните его в надёжном месте.

Ошибка «—shared-memory, or —named-pipe should be configured on NT OS»

Если при запуске mysqld вы столкнулись со следующей ошибкой:

[ERROR] [MY-010131] [Server] TCP/IP, --shared-memory, or --named-pipe should be configured on NT OS

то вам необходимо к команде запуска mysqld добавить флаг —shared-memory.

Связанные статьи:

  • MariaDB для Windows (100%)
  • Как обновить MySQL (100%)
  • Как обновить MariaDB в Windows (100%)
  • Как сделать резервную копию баз данных MySQL (MariaDB) в Windows без phpMyAdmin (100%)
  • Как в phpMyAdmin поменять настройки экспорта по умолчанию (100%)
  • Как запустить Apache на Windows (RANDOM — 50%)

I cannot figure out my MySQL root password; how can I find this out? Is there any file where this password is stored?

I am following this link but I do not have directadmin directory in local.

Ben's user avatar

Ben

51.1k36 gold badges127 silver badges148 bronze badges

asked Jun 5, 2012 at 9:54

Om3ga's user avatar

8

thanks to @thusharaK I could reset the root password without knowing the old password.

On ubuntu I did the following:

sudo service mysql stop
sudo mysqld_safe --skip-grant-tables --skip-syslog --skip-networking

Then run mysql in a new terminal:

mysql -u root

And run the following queries to change the password:

UPDATE mysql.user SET authentication_string=PASSWORD('password') WHERE User='root';
FLUSH PRIVILEGES;

In MySQL 5.7, the password field in mysql.user table field was removed, now the field name is ‘authentication_string’.

Quit the mysql safe mode and start mysql service by:

mysqladmin shutdown
sudo service mysql start

MagicLegend's user avatar

answered Oct 7, 2014 at 10:28

eeezyy's user avatar

eeezyyeeezyy

2,0811 gold badge15 silver badges18 bronze badges

7

You can’t view the hashed password; the only thing you can do is reset it!

Stop MySQL:

sudo service mysql stop

or

$ sudo /usr/local/mysql/support-files/mysql.server stop

Start it in safe mode:

$ sudo mysqld_safe --skip-grant-tables

(above line is the whole command)

This will be an ongoing command until the process is finished so open another shell/terminal window, log in without a password:

$ mysql -u root

mysql> UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';

MySQL 5.7 and over:

mysql> use mysql; 
mysql> update user set authentication_string=password('password') where user='root'; 

Exit the MySQL CLI:

mysql> exit 

Restart MySQL in normal mode, first stopping the safe mode instance:

$ mysqladmin -u root -p shutdown   # (when prompted, enter the new password just set)
$ sudo service mysql start

or

$ sudo /usr/local/mysql/support-files/mysql.server start

Your new password is ‘password’.

Reg Edit's user avatar

Reg Edit

6,4711 gold badge34 silver badges44 bronze badges

answered Sep 17, 2014 at 3:57

tk_'s user avatar

tk_tk_

15.8k8 gold badges80 silver badges89 bronze badges

5

MySQL 5.7 and above saves root in MySQL log file.

Please try this:

sudo grep 'temporary password' /var/log/mysqld.log

answered Mar 13, 2016 at 14:59

Vlad's user avatar

VladVlad

3,4271 gold badge30 silver badges24 bronze badges

2

One thing that tripped me up on a new install of MySQL and wondering why I couldn’t get the default password to work and why even the reset methods where not working.
Well turns out that on Ubuntu 18 the most recent version of MySQL server does not use password auth at all for the root user by default. So this means it doesn’t matter what you set it to, it won’t let you use it. It’s expecting you to login from a privileged socket.

mysql -u root -p

This will not work, even if you are using the correct password.

Instead, you need to use:

sudo mysql

that will work with out any password.
then once you in you need type in

 ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Password you want to use';

Then log out and now it will accept your password.

Jakov's user avatar

Jakov

8252 gold badges16 silver badges34 bronze badges

answered Apr 20, 2019 at 3:24

Kit Ramos's user avatar

Kit RamosKit Ramos

1,3931 gold badge13 silver badges32 bronze badges

2

Follow these steps to reset password in Windows system

  1. Stop Mysql service from task manager

  2. Create a text file and paste the below statement

MySQL 5.7.5 and earlier:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('yournewpassword');

MySQL 5.7.6 and later:

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

  1. Save as mysql-init.txt and place it in 'C' drive.

  2. Open command prompt and paste the following

C:> mysqld --init-file=C:\mysql-init.txt

Community's user avatar

answered Jul 1, 2016 at 15:13

Lokesh kumar Chippada's user avatar

2

You cannot find it. It is stored in a database, which you need the root password to access, and even if you did get access somehow, it is hashed with a one-way hash. You can reset it: How to Reset the Root Password

Kuro Neko's user avatar

answered Jun 5, 2012 at 9:55

lanzz's user avatar

lanzzlanzz

41.1k10 gold badges88 silver badges96 bronze badges

0

This worked for me:

On terminal type the following

$ sudo mysql -u root -p

Enter password://just press enter

mysql>

answered Feb 19, 2017 at 15:35

Light's user avatar

LightLight

1431 silver badge6 bronze badges

2

Unless the package manager requests you to type the root password during installation, the default root password is the empty string. To connect to freshly installed server, type:

shell> mysql -u root --password=
mysql>

To change the password, get back the unix shell and type:

shell> mysqladmin -u root --password= password root

The new password is ‘root’. Now connect to the server:

shell> mysql -u root --password=
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Oops, the password has changed. Use the new one, root:

shell> mysql -u root --password=root
...
blah, blah, blah : mysql welcome banner
...
mysql> 

Bingo! New do something interesting

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)

Maurycy

answered Jan 17, 2015 at 9:34

mszmurlo's user avatar

mszmurlomszmurlo

1,2181 gold badge13 silver badges26 bronze badges

1

As addition to the other answers, in a cpanel installation, the mysql root password is stored in a file named /root/.my.cnf. (and the cpanel service resets it back on change, so the other answers here won’t help)

answered Sep 24, 2015 at 7:48

Ohad Cohen's user avatar

Ohad CohenOhad Cohen

5,4763 gold badges38 silver badges35 bronze badges

0

you can view mysql root password , well i have tried it on mysql 5.5 so do not know about other new version well work or not

nano ~/.my.cnf

answered Oct 28, 2016 at 17:26

user889030's user avatar

user889030user889030

4,0993 gold badges45 silver badges51 bronze badges

0

The default password which worked for me after immediate installation of mysql server is : mysql

LinusGeffarth's user avatar

LinusGeffarth

26.1k29 gold badges115 silver badges170 bronze badges

answered Sep 29, 2014 at 8:43

Deepak Chaudhry's user avatar

1

The procedure changes depending the version of MySql. Follow the procedure exactly as described for your version:

  • HINTS — Read before the instructions page for your version of MySql*

  • In step 5: Instead of run CMD, create a shortcut on your desktop calling CDM.exe. Then right-click on the shortcut and select «Execute as Administrator».

  • In step 6: Skip the first proposed version of the command and execute the second one, the one with the —defaults-file parameter

  • Once you execute the command, if everything is ok, the CMD window remains open and the command of step 6 continues executing. Simply close the window (click ‘x’), and then force close MySQl from the Task Manager.

  • Delete the file with the SQL commands, and start again MySQL. The password must be changed now.

5.0
http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html

5.1
http://dev.mysql.com/doc/refman/5.1/en/resetting-permissions.html

… just change the version in the link (5.5, 5.6, 5.7)

ashatte's user avatar

ashatte

5,3828 gold badges38 silver badges50 bronze badges

answered Oct 31, 2013 at 0:28

JuanCamilo's user avatar

In your «hostname».err file inside the data folder MySQL works on, try to look for a string that starts with:

«A temporary password is generated for roor@localhost «

you can use

less /mysql/data/dir/hostname.err 

then slash command followed by the string you wish to look for

/"A temporary password"

Then press n, to go to the Next result.

answered Jan 11, 2016 at 5:06

nDCasT's user avatar

I solved this a different way, this may be easier for some.

I did it this way because I tried starting in safe mode but cannot connect with the error:
ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)

What I did was to connect normally as root:

$ sudo mysql -u root

Then I created a new super user:

mysql> grant all privileges on *.* to 'myuser'@'%' identified by 'mypassword' with grant option;
mysql> quit

Then log in as myuser

$ mysql -u myuser -p -h localhost

Trying to change the password gave me no errors but did nothing for me so I dropped and re-created the root user

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

The root user is now working with the new password

answered Sep 6, 2019 at 18:04

Trevorbest's user avatar

Using Debian / Ubuntu mysql packages, you can login with user debian-sys-maint, which has all the expected privileges, the password is stored in the file /etc/mysql/debian.cnf

answered Jan 21, 2022 at 9:51

Ohad Cohen's user avatar

Ohad CohenOhad Cohen

5,4763 gold badges38 silver badges35 bronze badges

System:

  • CentOS Linux 7
  • mysql Ver 14.14 Distrib 5.7.25

Procedure:

  1. Open two shell sessions, logging in to one as the Linux root user
    and the other as a nonroot user with access to the mysql command.

  2. In your root session, stop the normal mysqld listener and start a
    listener which bypasses password authentication (note: this is a
    significant security risk
    as anyone with access to the mysql
    command may access your databases without a password. You may want
    to close active shell sessions and/or disable shell access before
    doing this):

    # systemctl stop mysqld
    # /usr/sbin/mysqld --skip-grant-tables -u mysql &

  3. In your nonroot session, log in to mysql and set the mysql root password:

    $ mysql
    mysql> flush privileges;
    Query OK, 0 rows affected (0.00 sec)

    mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');
    Query OK, 0 rows affected, 1 warning (0.01 sec)

    mysql> quit;

  4. In your root session, kill the passwordless instance of mysqld and restore the normal mysqld listener to service:

    # kill %1
    # systemctl start mysqld

  5. In your nonroot session, test the new root password you configured above:

    $ mysql -u root -p
    Enter password:
    Welcome to the MySQL monitor. Commands end with ; or g.
    ...
    mysql>

answered Jun 24, 2019 at 17:57

CODE-REaD's user avatar

CODE-REaDCODE-REaD

2,6993 gold badges32 silver badges59 bronze badges

I was stuck with this problem for a couple of minutes and the following was the only solution that actually worked:
https://phoenixnap.com/kb/access-denied-for-user-root-localhost

  1. sudo mysql
  2. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'insert_password';
  3. mysql -u root -p

answered Jan 28, 2021 at 11:56

Ali Havasi's user avatar

Ali HavasiAli Havasi

5315 silver badges8 bronze badges

In case you already set a password in the past the mysql -uroot -p solution will not work,

In my case I used some of the answers above to solve this (Ubuntu 16). The result was:

sudo service mysql stop
sudo mysqld_safe --skip-grant-tables &

if you see this text in the screen:
mysqld_safe Directory ‘/var/run/mysqld’ for UNIX socket file don’t exists.
then do:

sudo mkdir -p /var/run/mysqld
sudo chown mysql:mysql /var/run/mysqld

sudo mysqld_safe --skip-grant-tables & # Look at the & at the end! 

Enter other terminal to set your password like this:

sudo mysql -u root

mysql> use mysql;
mysql> SET PASSWORD FOR 'root'@'localhost'=PASSWORD('__NEW__PASSWORD__');
mysql> flush privileges;
mysql> quit;

then restart the service and login

# end mysqld_safe in the other terminal
sudo service mysql start
sudo mysql -h 127.0.0.1 -uroot -p

answered May 4, 2021 at 18:04

user9869932's user avatar

user9869932user9869932

6,1033 gold badges55 silver badges47 bronze badges

For MySQL 5.5 on Windows 10

You can’t find the password as it is hashed in the table, so resetting it is the only option.

The solution of importing the new password script by .txt file, as offered by Lokesh kumar Chippada, didn’t work for me. I found that the command prompt just froze after initiating the import.

I added skip-grant-tables to the my.ini file as per the top the answer on this SO post by tonycoupland.

I was then able to login to mysql from the command line

$> mysql

and then in mysql

mysql> FLUSH PRIVILEGES;

mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');

See ‘B.3.3.2.3 Resetting the Root Password: Generic Instructions’ on mysql dev page. I have now removed skip-grant-tables from the my.ini file, and I can login as a root user using the new password I created.

answered May 6, 2022 at 2:16

Mr. J's user avatar

Mr. JMr. J

1,2892 gold badges17 silver badges39 bronze badges

Go to phpMyAdmin > config.inc.php > $cfg[‘Servers’][$i][‘password’] = »;

answered Oct 19, 2017 at 4:39

user3288185's user avatar

1

I cannot figure out my MySQL root password; how can I find this out? Is there any file where this password is stored?

I am following this link but I do not have directadmin directory in local.

Ben's user avatar

Ben

51.1k36 gold badges127 silver badges148 bronze badges

asked Jun 5, 2012 at 9:54

Om3ga's user avatar

8

thanks to @thusharaK I could reset the root password without knowing the old password.

On ubuntu I did the following:

sudo service mysql stop
sudo mysqld_safe --skip-grant-tables --skip-syslog --skip-networking

Then run mysql in a new terminal:

mysql -u root

And run the following queries to change the password:

UPDATE mysql.user SET authentication_string=PASSWORD('password') WHERE User='root';
FLUSH PRIVILEGES;

In MySQL 5.7, the password field in mysql.user table field was removed, now the field name is ‘authentication_string’.

Quit the mysql safe mode and start mysql service by:

mysqladmin shutdown
sudo service mysql start

MagicLegend's user avatar

answered Oct 7, 2014 at 10:28

eeezyy's user avatar

eeezyyeeezyy

2,0811 gold badge15 silver badges18 bronze badges

7

You can’t view the hashed password; the only thing you can do is reset it!

Stop MySQL:

sudo service mysql stop

or

$ sudo /usr/local/mysql/support-files/mysql.server stop

Start it in safe mode:

$ sudo mysqld_safe --skip-grant-tables

(above line is the whole command)

This will be an ongoing command until the process is finished so open another shell/terminal window, log in without a password:

$ mysql -u root

mysql> UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';

MySQL 5.7 and over:

mysql> use mysql; 
mysql> update user set authentication_string=password('password') where user='root'; 

Exit the MySQL CLI:

mysql> exit 

Restart MySQL in normal mode, first stopping the safe mode instance:

$ mysqladmin -u root -p shutdown   # (when prompted, enter the new password just set)
$ sudo service mysql start

or

$ sudo /usr/local/mysql/support-files/mysql.server start

Your new password is ‘password’.

Reg Edit's user avatar

Reg Edit

6,4711 gold badge34 silver badges44 bronze badges

answered Sep 17, 2014 at 3:57

tk_'s user avatar

tk_tk_

15.8k8 gold badges80 silver badges89 bronze badges

5

MySQL 5.7 and above saves root in MySQL log file.

Please try this:

sudo grep 'temporary password' /var/log/mysqld.log

answered Mar 13, 2016 at 14:59

Vlad's user avatar

VladVlad

3,4271 gold badge30 silver badges24 bronze badges

2

One thing that tripped me up on a new install of MySQL and wondering why I couldn’t get the default password to work and why even the reset methods where not working.
Well turns out that on Ubuntu 18 the most recent version of MySQL server does not use password auth at all for the root user by default. So this means it doesn’t matter what you set it to, it won’t let you use it. It’s expecting you to login from a privileged socket.

mysql -u root -p

This will not work, even if you are using the correct password.

Instead, you need to use:

sudo mysql

that will work with out any password.
then once you in you need type in

 ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Password you want to use';

Then log out and now it will accept your password.

Jakov's user avatar

Jakov

8252 gold badges16 silver badges34 bronze badges

answered Apr 20, 2019 at 3:24

Kit Ramos's user avatar

Kit RamosKit Ramos

1,3931 gold badge13 silver badges32 bronze badges

2

Follow these steps to reset password in Windows system

  1. Stop Mysql service from task manager

  2. Create a text file and paste the below statement

MySQL 5.7.5 and earlier:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('yournewpassword');

MySQL 5.7.6 and later:

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

  1. Save as mysql-init.txt and place it in 'C' drive.

  2. Open command prompt and paste the following

C:> mysqld --init-file=C:\mysql-init.txt

Community's user avatar

answered Jul 1, 2016 at 15:13

Lokesh kumar Chippada's user avatar

2

You cannot find it. It is stored in a database, which you need the root password to access, and even if you did get access somehow, it is hashed with a one-way hash. You can reset it: How to Reset the Root Password

Kuro Neko's user avatar

answered Jun 5, 2012 at 9:55

lanzz's user avatar

lanzzlanzz

41.1k10 gold badges88 silver badges96 bronze badges

0

This worked for me:

On terminal type the following

$ sudo mysql -u root -p

Enter password://just press enter

mysql>

answered Feb 19, 2017 at 15:35

Light's user avatar

LightLight

1431 silver badge6 bronze badges

2

Unless the package manager requests you to type the root password during installation, the default root password is the empty string. To connect to freshly installed server, type:

shell> mysql -u root --password=
mysql>

To change the password, get back the unix shell and type:

shell> mysqladmin -u root --password= password root

The new password is ‘root’. Now connect to the server:

shell> mysql -u root --password=
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Oops, the password has changed. Use the new one, root:

shell> mysql -u root --password=root
...
blah, blah, blah : mysql welcome banner
...
mysql> 

Bingo! New do something interesting

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)

Maurycy

answered Jan 17, 2015 at 9:34

mszmurlo's user avatar

mszmurlomszmurlo

1,2181 gold badge13 silver badges26 bronze badges

1

As addition to the other answers, in a cpanel installation, the mysql root password is stored in a file named /root/.my.cnf. (and the cpanel service resets it back on change, so the other answers here won’t help)

answered Sep 24, 2015 at 7:48

Ohad Cohen's user avatar

Ohad CohenOhad Cohen

5,4763 gold badges38 silver badges35 bronze badges

0

you can view mysql root password , well i have tried it on mysql 5.5 so do not know about other new version well work or not

nano ~/.my.cnf

answered Oct 28, 2016 at 17:26

user889030's user avatar

user889030user889030

4,0993 gold badges45 silver badges51 bronze badges

0

The default password which worked for me after immediate installation of mysql server is : mysql

LinusGeffarth's user avatar

LinusGeffarth

26.1k29 gold badges115 silver badges170 bronze badges

answered Sep 29, 2014 at 8:43

Deepak Chaudhry's user avatar

1

The procedure changes depending the version of MySql. Follow the procedure exactly as described for your version:

  • HINTS — Read before the instructions page for your version of MySql*

  • In step 5: Instead of run CMD, create a shortcut on your desktop calling CDM.exe. Then right-click on the shortcut and select «Execute as Administrator».

  • In step 6: Skip the first proposed version of the command and execute the second one, the one with the —defaults-file parameter

  • Once you execute the command, if everything is ok, the CMD window remains open and the command of step 6 continues executing. Simply close the window (click ‘x’), and then force close MySQl from the Task Manager.

  • Delete the file with the SQL commands, and start again MySQL. The password must be changed now.

5.0
http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html

5.1
http://dev.mysql.com/doc/refman/5.1/en/resetting-permissions.html

… just change the version in the link (5.5, 5.6, 5.7)

ashatte's user avatar

ashatte

5,3828 gold badges38 silver badges50 bronze badges

answered Oct 31, 2013 at 0:28

JuanCamilo's user avatar

In your «hostname».err file inside the data folder MySQL works on, try to look for a string that starts with:

«A temporary password is generated for roor@localhost «

you can use

less /mysql/data/dir/hostname.err 

then slash command followed by the string you wish to look for

/"A temporary password"

Then press n, to go to the Next result.

answered Jan 11, 2016 at 5:06

nDCasT's user avatar

I solved this a different way, this may be easier for some.

I did it this way because I tried starting in safe mode but cannot connect with the error:
ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)

What I did was to connect normally as root:

$ sudo mysql -u root

Then I created a new super user:

mysql> grant all privileges on *.* to 'myuser'@'%' identified by 'mypassword' with grant option;
mysql> quit

Then log in as myuser

$ mysql -u myuser -p -h localhost

Trying to change the password gave me no errors but did nothing for me so I dropped and re-created the root user

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

The root user is now working with the new password

answered Sep 6, 2019 at 18:04

Trevorbest's user avatar

Using Debian / Ubuntu mysql packages, you can login with user debian-sys-maint, which has all the expected privileges, the password is stored in the file /etc/mysql/debian.cnf

answered Jan 21, 2022 at 9:51

Ohad Cohen's user avatar

Ohad CohenOhad Cohen

5,4763 gold badges38 silver badges35 bronze badges

System:

  • CentOS Linux 7
  • mysql Ver 14.14 Distrib 5.7.25

Procedure:

  1. Open two shell sessions, logging in to one as the Linux root user
    and the other as a nonroot user with access to the mysql command.

  2. In your root session, stop the normal mysqld listener and start a
    listener which bypasses password authentication (note: this is a
    significant security risk
    as anyone with access to the mysql
    command may access your databases without a password. You may want
    to close active shell sessions and/or disable shell access before
    doing this):

    # systemctl stop mysqld
    # /usr/sbin/mysqld --skip-grant-tables -u mysql &

  3. In your nonroot session, log in to mysql and set the mysql root password:

    $ mysql
    mysql> flush privileges;
    Query OK, 0 rows affected (0.00 sec)

    mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');
    Query OK, 0 rows affected, 1 warning (0.01 sec)

    mysql> quit;

  4. In your root session, kill the passwordless instance of mysqld and restore the normal mysqld listener to service:

    # kill %1
    # systemctl start mysqld

  5. In your nonroot session, test the new root password you configured above:

    $ mysql -u root -p
    Enter password:
    Welcome to the MySQL monitor. Commands end with ; or g.
    ...
    mysql>

answered Jun 24, 2019 at 17:57

CODE-REaD's user avatar

CODE-REaDCODE-REaD

2,6993 gold badges32 silver badges59 bronze badges

I was stuck with this problem for a couple of minutes and the following was the only solution that actually worked:
https://phoenixnap.com/kb/access-denied-for-user-root-localhost

  1. sudo mysql
  2. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'insert_password';
  3. mysql -u root -p

answered Jan 28, 2021 at 11:56

Ali Havasi's user avatar

Ali HavasiAli Havasi

5315 silver badges8 bronze badges

In case you already set a password in the past the mysql -uroot -p solution will not work,

In my case I used some of the answers above to solve this (Ubuntu 16). The result was:

sudo service mysql stop
sudo mysqld_safe --skip-grant-tables &

if you see this text in the screen:
mysqld_safe Directory ‘/var/run/mysqld’ for UNIX socket file don’t exists.
then do:

sudo mkdir -p /var/run/mysqld
sudo chown mysql:mysql /var/run/mysqld

sudo mysqld_safe --skip-grant-tables & # Look at the & at the end! 

Enter other terminal to set your password like this:

sudo mysql -u root

mysql> use mysql;
mysql> SET PASSWORD FOR 'root'@'localhost'=PASSWORD('__NEW__PASSWORD__');
mysql> flush privileges;
mysql> quit;

then restart the service and login

# end mysqld_safe in the other terminal
sudo service mysql start
sudo mysql -h 127.0.0.1 -uroot -p

answered May 4, 2021 at 18:04

user9869932's user avatar

user9869932user9869932

6,1033 gold badges55 silver badges47 bronze badges

For MySQL 5.5 on Windows 10

You can’t find the password as it is hashed in the table, so resetting it is the only option.

The solution of importing the new password script by .txt file, as offered by Lokesh kumar Chippada, didn’t work for me. I found that the command prompt just froze after initiating the import.

I added skip-grant-tables to the my.ini file as per the top the answer on this SO post by tonycoupland.

I was then able to login to mysql from the command line

$> mysql

and then in mysql

mysql> FLUSH PRIVILEGES;

mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');

See ‘B.3.3.2.3 Resetting the Root Password: Generic Instructions’ on mysql dev page. I have now removed skip-grant-tables from the my.ini file, and I can login as a root user using the new password I created.

answered May 6, 2022 at 2:16

Mr. J's user avatar

Mr. JMr. J

1,2892 gold badges17 silver badges39 bronze badges

Go to phpMyAdmin > config.inc.php > $cfg[‘Servers’][$i][‘password’] = »;

answered Oct 19, 2017 at 4:39

user3288185's user avatar

1



The default user for MySQL is root and by default it has no password.

If you set a password for MySQL and you can’t recall it, you can always reset it and choose another one.

Windows

  1. Make sure that MySQL Server is not running. Open Task Manager, search for the MySQL process and force stop it.

  2. Create a new text file that will contain the statement below:

     SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');

    Replace the password with the new one

  3. Save the file with the mysql-init name in C:. The path should look like this:

     C:mysql-init.txt
  4. Open the Start menu, enter Run then write cmd to open the command prompt

  5. Go to the MySQL server bin folder

     cd "C:Program FilesMySQLMySQL Server 5.6bin"

    If you installed MySQL with a different path, adjust the cd

  6. Run it with the mysql-init file

     mysqld --init-file=C:\mysql-init.txt

    If MySQL was installed using the Wizard, add the defaults file command:

     mysqld
           --defaults-file="C:\ProgramData\MySQL\MySQL Server 5.6\my.ini"
           --init-file=C:\mysql-init.txt
  7. After MySQL server started, delete the mysql-init file.

DbSchema Database Designer

General

Alternatively, you can use a more general method that works on every system, but it’s less safe.

  1. Stop MySQL

  2. Restart it with the --skip-grant-tables option

     sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &
  3. Connect to MySQL server using the mysql client

     mysql -u root
  4. Reload all grant tables by executing:

     FLUSH PRIVILEGES;
  5. Set the new password for your account:

     SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');
  6. Stop the server and restart it normally. Now you should be able to connect using the root username and your new password.

Share this blog post on Twitter, Facebook, and LinkedIn

Visually Manage MySql using DbSchema

DbSchema is a MySQL client and visual designer. DbSchema has a free Community Edition, which can be downloaded here.
DbSchema main features include:

DbSchema Designer alt >

Interactive Diagrams

Design tables, column and foreign keys directly in diagrams.


Connection Dialog alt >

Simple Connection Dialog

Choose the database location, the user and password, and simply get connected.


Relational Data Explorer alt >

Relational Data Explorer

Explore data from multiple tables simultaneously, using foreign keys or virtual foreign keys.


Query Builder alt >

Query Builder

Create SQL Queries using the mouse.


SQL Query Editor alt >

SQL Query Editor

Edit and execute SQL Queries


Schema Synchronization alt >

Design Schema in Team & Schema Deployment

DbSchema is using the design model, a copy of the schema structure, independent of the database.
The design model can be saved to file and shared in a team.
Connecting to another database you may compare the design model with the database, commit the differences or merge them in the design model.


Dark Theme alt >

Dark Theme

Configurable styles & dark theme.


Many features are available in the free Community edition.
The Pro edition adds capabilities to save the design to the model file, design schema in team and deploy the schema on multiple databases.

DbSchema can be downloaded for free. No registration is required.

In MySQL, by default, the username is root and there’s no password.

If during the installation process, you accidentally put a password in and don’t remember, here is how to reset the password:

  • Stop the MySQL server if it is running, then restart it with the –skip-grant-tables option.
sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &

It allows you to connect without a password and with all privileges and disables account-management statements such as ALTER USER and SET PASSWORD, which will be used later on to reset password. --skip-networking is enabled to automatically to prevent remote connections since it’s very insecure.

  • Then connect to the MySQL Server using the mysql client:
  • Then run this command to reload the grant tables:
  • Now you can be able to set a new password for the root account:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

It’s done, stop the server and restart it normally. Now you can connect to the MySQL Server with the new password.


Need a good GUI Tool for MySQL? TablePlus is a modern, native tool with an elegant UI that allows you to simultaneously manage multiple databases such as MySQL, PostgreSQL, SQLite, Microsoft SQL Server and more.


Download TablePlus for Mac. It’s free anyway!

Not on Mac? Download TablePlus for Windows.

On Linux? Download TablePlus for Linux

Need a quick edit on the go? Download TablePlus for iOS.

TablePlus GUI Tool MySQL

Введение

Доступы к серверам и сервисам нужно тщательно хранить, никому их не передавать и не терять. Но иногда случаются ситуации, когда пароли все-таки теряются или после смены их забывают записать, восстановить такой пароль тоже нет возможности. Если вы забыли пароль от root-пользователя MySQL — не отчаивайтесь, пароль root в MySQL легко сменить.

Важно понимать, что у вас должны быть права администратора на том сервере, где установлен MySQL-сервер. Это может быть либо root-пользователь напрямую, либо доступ через sudo.

Все описанные ниже действия нужно выполнять именно на этом сервере, то есть удаленно сменить пароль от root-пользователя не удастся.

Возможности MySQL в «Облачных базах данных»

Подробнее

Самый простой способ для последних версий

В версиях MySQL, начиная с 5.7, можно логиниться в MySQL от root-пользователя без пароля, если системный пользователь тоже root. Это позволяет подключиться к MySQL как root-пользователь без ввода пароля, а потом изменить его. Это возможно если для пользователя root используется плагин аутентификации auth_socket.

Выполните команду:

    sudo mysql

Вы подключитесь к MySQL-серверу как root-пользователь. Теперь можно сбросить пароль одной командой. Вместо 12345 укажите свой пароль:

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

Это самый простой способ, доступный в последних версиях MySQL при использовании плагина аутентификации auth_socket.

Сбросить пароль root в MySQL с помощью SKIP-GRANT-TABLES

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

Для начала нужно остановить сервер:

    sudo systemctl stop mysql

Теперь отредактируем service-файл, который запускает MySQL. Выполним команду:

    sudo systemctl edit mysql

Откроется текстовый редактор, в котором мы можем переопределить дефолтный файл запуска. Вставим в него следующую конфигурацию:

    [Service]
ExecStart=
ExecStart=/usr/sbin/mysqld --skip-grant-tables --skip-networking

Мы указываем, что сервер нужно запустить без проверки grant-таблиц, а также ограничить подключения по сети. Сохраните файл и выйдите из текстового редактора. Теперь нужно обновить конфигурацию systemd, чтобы он учитывал наш новый конфиг, а затем можно запустить сервер:

    sudo systemctl daemon-reload
sudo systemctl start mysql

Теперь мы можем залогиниться под учетной записью root без ввода пароля. Для этого нам даже не нужно быть root или использовать sudo:

    mysql -u root

Так как мы запустили сервер без проверки полномочий, сначала нам нужно применить таблицу привилегий, чтобы мы могли записать в нее новый пароль. Вместо 12345 укажите свой пароль:

    FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY '12345';

Выходим из MySQL и возвращаем настройки запуска по умолчанию. Для этого нам нужно удалить service-файл для systemd, перечитать конфигурацию и снова запустить сервер БД:

    sudo systemctl revert mysql
sudo systemctl daemon-reload
sudo systemctl restart mysql

Все, мы перезапустили MySQL-сервер и теперь можем залогиниться с новым паролем.

Сбросить пароль с помощью init-file

Еще один способ — написать init-файл. Это файл, который MySQL считывает перед запуском. В нем можно указать различные команды, в том числе установить пароль любого пользователя.

Создайте простой текстовый файл, например в вашей домашней директории. Назвать его можно как угодно. Вставьте в этот файл команду для смены пароля. Вместо 12345 укажите свой настоящий пароль:

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

Теперь нужно остановить MySQL-сервер, чтобы при следующем запуске ему можно было указать путь к нашему init-файлу. Выполните команду:

    sudo systemctl stop mysql

Теперь снова запустим сервер, при этом указав путь к созданному нами файлу:

    sudo mysqld --user=mysql --init-file=/path/to/init-file &

После запуска этой команды в консоли отобразится PID этого процесса, например 7508. Значит все прошло успешно, MySQL-сервер запустился и выполнил нашу команду. Теперь нам нужно его остановить, удалить init-файл и запустить сервер обычным способом:

    sudo kill -15 7508
rm /path/to/init-file
sudo systemctl start mysql

Заключение

Мы рассмотрели три разных способа сброса пароля для root-пользователя. Теперь MySQL-сервер работает в стандартном режиме, а у вас есть root-доступ к базе данных.

Понравилась статья? Поделить с друзьями:
  • Mysql не является внутренней или внешней командой windows 10
  • Mysql не ставится на windows 7
  • Mysql не запускается служба windows 10
  • Mysql не запускается после перезагрузки windows
  • Mysql настройка сервера windows server 2022