Mysql change root password windows

Last Updated :
07 Apr, 2025

Ever locked yourself out of your own database? It happens to the best of us! If you’ve forgotten your MySQL root password on a Windows machine, don’t panic. MySQL is a powerful database management system, and the root user has complete control over it meaning losing access can feel like a nightmare. But with the right steps, you can reset that password and regain control in no time.

In this step-by-step guide, we’ll walk you through the process of resetting your MySQL root password using the Command Prompt (CMD). Also, the process we are going to explain the in the below article will work for both Windows 11 and Windows 10.

How-to-Reset-MySQL-Root-Password-in-Windows-Using-CMD-copy

Reset MySQL Root Password in Windows Using CMD

How to Reset MySQL Root Password in Windows using CMD?

Note: Before Resetting MySQL Root Password, make sure that you are Log in to your system as Administrator.

Step 1: Stop the MySQL server

  • Press Win+R and type the following command in the Run box and Click OK.
Command: services.msc

  • Scroll down the list of services to find the MySQL service. Right-click that entry then left-clicks Stop.

For detailed guide, check out: How to Stop MySQL Server on Windows and Linux?

Step 2: Launch a Text Editor

  • Click on the menu and search for Notepad.
  • Alternatively, press Ctrl + Alt + N to open Notepad.

Step 3: Create a New Text File with the Password Command

  • Enter the following command to the text editor:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword';

Note: Copy-paste this command to avoid any mistake. Make a new password and Replace ‘NewPassword’ with it.

How-to-Reset-MySQL-Root-Password-in-Windows_2

  • Use the File > Save As menu to save the file to the root of your hard drive (C:\ ). Choose a filename that makes sense, such as mysql-init.txt.

Consequently, the localhost command will make the password change on your local system. If you’re trying to change the password on a system over the network, substitute the hostname for localhost.

Step 4: Open a Command Prompt

  • Press Ctrl+Shift+Esc.
  • Then, click on the File menu > Run new task.
  • Type cmd.exe, and check the box to run as administrator.
  • Click OK.

Step 5: Restart the MySQL Server with Your New Config File

  • Navigate to the MySQL directory using the command prompt:
cd "C:\Program Files\MySQL\MySQL Server 8.0\bin"

Accordingly, the command line will show that you’re working in this folder.

  • Enter the following:
mysqld --init-file=C:\\mysql-init.txt

Note:

  • There are two slashes after the C: prompt.
  • Also, if you choose a different name in Step 2, use the same name after the double slash.

Step 6: Clean up

Now, you can log into your MySQL server as root using the new password.

  • Double-check to make sure it works. If you have unique configuration options (such as launching MySQL with a -defaults-file option), go ahead and do so.
  • Once MySQL launches, and you’ve confirmed the password change, delete the C:\myswl-init.txt file.

At this stage, you have successfully changed MySQL root password.

Conclusion

Resetting your MySQL root password on Windows is a straightforward process when using the Command Prompt. By following the steps outlined in this guide, you can efficiently recover your MySQL root password using CMD and regain control over your database. Whether you’re a seasoned MySQL user or a beginner, this method ensures that you can handle password issues without unnecessary hassle. Keep this guide handy for future reference, so you’re always prepared to reset your MySQL root password in Windows using CMD.

Also Read

  • MySQL | Change User Password
  • MySQL | Common MySQL Queries
  • learn SQL in 30 Days – From Basic to Advanced Level!
  • How to Find the Wi-Fi Password Using CMD in Windows?

Получение доступа к базам данных является важной задачей при управлении серверами и обслуживании веб-приложений. Одной из самых распространенных и мощных систем управления базами данных (СУБД) является MySQL. Как администратор базы данных, вы храните важную информацию, и пароль root MySQL играет решающую роль в обеспечении безопасности и целостности данных.

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

В данной статье мы представим вам методы и инструменты, которые помогут сбросить пароль root в MySQL и восстановить полный контроль над вашей базой данных. Мы охватим различные подходы, начиная от использования официальных инструментов MySQL, таких как mysqladmin и mysqld_safe, до редактирования файлов конфигурации и внесения изменений в систему.

Стоит отметить, что восстановление доступа к паролю root MySQL является сложной задачей и требует определенных знаний и навыков. Поэтому рекомендуем внимательно ознакомиться с инструкциями, чтобы избежать возможных проблем или потери данных.

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

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

MySQL не использует PAM и пароль от SSH не подойдёт. Пароль root задаётся в процессе установки сервера баз данных, на этапе формирования таблиц привилегий.

Если после попытки входа вместо приветствия база данных выдаёт ошибку ERROR 1045: Access denied for user 'root'@'localhost', значит нужно сбросить root-пароль.

Чтобы в MySQL 8 сбросить пароль root, необходимо пройти несложную процедуру. Она одинаково подходит как для традиционного MySQL, так и для MariaDB. Они полностью совместимы и имеют одинаковые команды.

В Ubuntu сбросить пароль root для MySQL можно такими же методами, как и в Debian, конкретной привязки к ОС нет. Небольшое отличие возможно для CentOS 7, это мы отметим ниже в соответствующем пункте.

dbaas

Как в MySQL сбросить пароль root методом skip-grant-tables

Достаточно распространённый способ, ввиду его простоты. Приводим пошаговый план этой операции:

Шаг 1

Остановим службу базы данных:

service mysqld stop

Шаг 2

Запускаем службу без таблиц привилегий:

mysqld --skip-grant-tables&

Амперсанд в конце позволяет запустить службу в фоне и она не занимает отдельное окно терминала.

Шаг 3

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

mysql -u root

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

Шаг 4

Подключаем таблицы привилегий:

FLUSH PRIVILEGES;

В ответ получаем: Query OK, 0 rows affected.

Шаг 5

Установим новый пароль суперпользователя root:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'ПАРОЛЬ';

Если этот запрос не сработал, попробуйте:

UPDATE `mysql`.`user` SET `password`=password('ПАРОЛЬ') WHERE `user`='root';

Или:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('ПАРОЛЬ');

На CentOS 7 сбросить пароль MySQL root можно, выполнив команду:

UPDATE `mysql`.`user` SET ` authentication_string`=password('ПАРОЛЬ') WHERE `user`='root';

Об успешности выполнения можно судить по ответу Query OK, 0 rows affected. Пароль может быть даже пустым значением, но в таком случае будет потеряна возможность подключения к серверу любыми другими способами, кроме командной строки. Пароль изменяется сразу после ввода команды. Проверить можно, например, подключившись через phpMyAdmin, если не было передано пустое значение.

Шаг 6

Выход из mysql:

quit;

В ответ получим Bye, вернётся обычный терминал.

Шаг 7

Запускаем сервер баз данных в штатном режиме:

service mysqld start

Как в MySQL сбросить пароль root на ОС Windows

Сброс пароля суперпользователя MySQL под ОС Windows схож с процедурой сброса root-пароля СУБД для Linux-систем. Некоторые отличия могут быть только в процессе поиска и запуска службы самой базы данных. Из-за разных названий служб MySQL и MariaDB нет привязки к названию «mysql», и иногда необходимо указывать конкретное название службы. Рассмотрим пошагово сброс пароля суперпользователя базы данных для ОС Windows.

Шаг 1

Открываем интерпретатор команд в режиме Администратора. В этом случае есть разница, какая база данных установлена, в Windows службы имеют различные названия. Проверяем, какая установлена:

Для MySQL:

sc qc "mysql"

Для MariaDB:

sc qc "mariadb"

В случае, если служба отсутствует, будет показано сообщение «Указанная служба не установлена». При успешном выполнении будет выведена основная служебная информация.

Шаг 2

Если не установлена переменная %PATH%, необходимо перейти в папку с исполняемым файлом службы базы данных, путь можно определить по ответу sc qc в «Имя_двоичного_файла». В нашем случае это С:\localhost\mariadb\bin\.

cd C:\localhost\mariadb\bin\

Если диск другой, то переходим на него, указав букву диска, например:

D:

Шаг 3

Остановим уже запущенную службу:

Для MySQL:

net stop mysql

Для MariaDB:

net stop mariadb

Шаг 4

Откроем окно дополнительного интерпретатора командой start. В отличие от Linux, в Windows амперсанд в конце команды не работает, а при запуске службы она не даст более вводить команды до окончания сессии (нажатии CTRL+C).

Шаг 5

Запуск сервера без привилегий (идентично для MySQL и MariaDB):

mysqld --skip-grant-tables

Шаг 6

Во втором окне вводим:

mysql -u root -p

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

Шаг 7

Для начала необходимо выполнить команду:

FLUSH PRIVILEGES;

Без этой начальной команды можно получить ошибку при смене пароля: «ERROR 1290: The MariaDB server is running with the —skip-grant-tables option so it cannot execute this statement». 

Шаг 8

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

ALTER USER 'root'@'localhost' IDENTIFIED BY 'ПАРОЛЬ';

Примечание: если команда не сработала, попробуйте варианты из пятого шага инструкции для Linux-систем.

Закрываем окно интерпретатора с запущенной временной версией базы данных или нажимаем CTRL+C.

Шаг 9

Запускаем системную службу:

Для MySQL:

net start mysql

Для MariaDB:

net start mariadb

Заключение

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

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

  • Используйте сложные пароли, состоящие из комбинации букв, цифр и специальных символов, а также регулярно меняйте их. 
  • Ограничьте доступ к базе данных только необходимым пользователям, чтобы минимизировать риски несанкционированного доступа. 
  • Регулярно обновляйте систему MySQL, чтобы устранять известные уязвимости и получать последние исправления безопасности.
  • Регулярно создавайте резервные копии базы данных. Это ваша страховка в случае потери данных или сбоя системы. Разработайте стратегию резервного копирования, определите частоту и методы создания резервных копий, а также проверяйте их восстанавливаемость, чтобы быть уверенными в возможности восстановления данных.
  • Помните о важности обучения и саморазвития в области управления базами данных. Будьте в курсе последних тенденций, новых функций и инструментов MySQL. Воспользуйтесь обучающими ресурсами, участвуйте в семинарах и конференциях, а также общайтесь с опытными профессионалами в этой области. Постоянное обновление своих знаний и навыков поможет вам эффективно управлять базой данных и решать возникающие проблемы.

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

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

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

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

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

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

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

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

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

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

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

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

cd C:\Server\bin\mysql-8.0\bin\

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

.\mysql --version

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

C:\Server\bin\mysql-8.0\bin\mysqld.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:\Server\bin\mysql-8.0\bin\

И подключаемся к серверу 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 (RANDOM — 50%)

Table of Contents

  1. Introduction
  2. Solution #1: Reset Password Using MySQL Command Line
  3. Solution #2: Use MySQL Installer for Windows
  4. Solution #3: Resetting Password from a MySQL Initialization File
  5. Conclusion

Introduction

Forgetting the root password to your MySQL database can be a significant hindrance when managing databases. Fortunately for Windows users, MySQL 8 provides several ways to reset the root password with varying degrees of difficulty. This guide will discuss multiple solutions to reset your MySQL root password in Windows environments.

Solution #1: Reset Password Using MySQL Command Line

One of the simplest ways to reset the MySQL root password is to use the MySQL command-line tool. This option requires initiating MySQL with a special option to bypass the need for a password.

  1. Stop the MySQL server if it is currently running.
  2. Open the command prompt as an administrator.
  3. Navigate to your MySQL bin directory, such as C:\Program Files\MySQL\MySQL Server 8.0\bin
  4. Run the server in safe mode with skip-grant-tables:
    mysqld --skip-grant-tables
  5. In a new command prompt window, log in to MySQL as the root user:
    mysql -u root mysql
  6. Reset the root password:
    FLUSH PRIVILEGES;
    ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
    
  7. Restart the MySQL service normally.

Notes: Using this method, MySQL runs without user privilege restrictions, making it less secure. Perform these steps cautiously and restart the normal operation as soon as possible.

Solution #2: Use MySQL Installer for Windows

The MySQL Installer for Windows provides a user-friendly graphical interface for configuring server settings, including resetting user passwords.

  1. Launch the MySQL Installer from the Start Menu or from its installation directory.
  2. Select ‘Reconfigure’ next to the MySQL Server component.
  3. Navigate through the setup process until you reach the ‘Accounts and Roles’ section.
  4. Choose ‘Change root password’, enter a new password, and confirm the change.
  5. Complete the configuration process and apply the changes.

Notes: This approach is user-friendly but requires that you have the MySQL Installer configured initially. It is an easy method for beginners and doesn’t involve interacting with command-line interfaces.

Solution #3: Resetting Password from a MySQL Initialization File

If you’re unable to use either of the previous methods, creating a custom MySQL initialization file can assist in resetting the password.

  1. Create a text file on your server and include the following MySQL statements that will reset the root password to ‘new_password’:
    ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
    FLUSH PRIVILEGES;
    
  2. Save the file with an appropriate name, such as reset_password.sql.
  3. Stop the MySQL service using the Services management console or with the following command line:
    net stop mysql
  4. Restart the MySQL server with the --init-file option pointing to your reset script:
    mysqld --init-file=C:\path\to\reset_password.sql
  5. Once the server has restarted, remove the --init-file option to prevent the script from running on subsequent starts.
  6. Start the MySQL service normally.

Notes: When using an initialization file, you temporarily store the new password in plaintext, which can pose a security risk. Ensure the file’s security during this process and delete it immediately after use.

Conclusion

In conclusion, resetting the root password in MySQL 8 on a Windows system can be achieved through various methods, depending on your familiarity with MySQL and the level of access you have to the system. The most straightforward method is to use the MySQL command line with the skip-grant-tables option, but for a more graphical approach, the MySQL Installer for Windows is preferable. For situations where the other options might not be viable, resorting to the initialization file method is a reliable workaround. Always consider the security implications when handling passwords and choose the solution that best fits your situation and skill level.

Home » KB » Security » How to Reset or Change MySQL Root Password on Linux or Windows

MySQL is a popular database management system for web application software. Like many web services, MySQL has an administrator-level or root password. The root password allows a user to perform all top-level functions in the database.

If you’ve never set a root password on your MySQL database, you should be able to connect to it. However, this is not a good security practice, as anyone can access your database.

If your database has a root password, but you lost track of it, this guide will help you reset a MySQL root password on Linux and Windows.

How to reset or change MySQL root password on Linux or Windows.

Prerequisites

  • An existing MySQL database.
  • Access to a Linux or Windows server running MySQL.
  • Administrator privileges.
  • A text editor.
  • Access to a command-line interface (or terminal).

How to Change MySQL User Root Password in Linux

Follow the steps outlined below to change your MySQL root password in Linux. For this tutorial, we will use Ubuntu 22.

Step 1: Log in as MySQL User

Log into your system as the user that you use to start and run the MySQL server. You can also log in as root, but in that case, you must use the --user=mysql -p option when starting the mysqld service later in step 5.

Starting the server as root creates root-owned files in the data directory, which can cause permission-related issues for future server startups.

Step 2: Stop the MySQL Server

Before changing the password, stop the MySQL server if it is active. Run the following command to stop the mysqld process:

sudo service mysql stop

The command stops the MySQL server. Alternatively, run the following command to kill all running instances of the MySQL server:

killall mysqld

Step 3: Create a Password File

Create a file in which you will specify the new password. Follow the steps below:

1. Create a new text file using your favorite text editor. In this tutorial, we will use nano. The syntax is:

sudo nano /home/[username]/mysql-init

Replace [username] with your actual username on your system.

2. Next, add the following line to the file:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword';
  • Replace the NewPassword with the password you want to use. Include the single-quote marks and the semicolon at the end. Make sure to use a strong and secure password.
  • The command works for the machine you’re currently using. Replace localhost with the appropriate hostname if you’re connecting to a different system.
Creating a password file for MySQL in Ubuntu.

3. Save the file with Ctrl+O and exit the editor with Ctrl+X. If you are not logged in with the user account that you use for running the server, set the file permissions to allow the MySQL user to read the file.

Step 4: Apply the Changes

To apply the password change, use the following syntax:

sudo mysqld --init-file=/home/[username]/mysql-init &

Make sure to replace [username] with your actual username on your system. For example:

Changing the MySQL root password in Linux.

The command applies the text-file password change. The output shows the process ID (PID) of the service that was started in the background.

Step 5: Restart the Server

Restart the MySQL server after changing the root password to apply the changes. Enter the command below:

sudo service mysql start

Wait until the process completes.

Step 6: Log in and Clean Up

Log into your MySQL server using the root account and verify the new password works.

Logging into the MySQL server on Ubuntu.

If everything works, you can delete the file you created in Step 3.

How to Reset MySQL Root Password in Windows

The steps below show how to reset the MySQL root password in Windows. In this tutorial, we will use Windows 11, but the process works for Windows 10 as well.

Step 1: Log in as Administrator

Log in to the Windows machine as an administrator. Administrative access ensures that you have the necessary rights to modify system-level settings.

Step 2: Stop MySQL server

1. Press Win+R (hold the Windows/Super key, and press r).

2. In the Run box, type services.msc and press Enter.

3. Scroll down the list of services to find the MySQL service. Right-click the entry and select Stop.

Stopping the MySQL service on Windows.

Step 3: Create Password File

The password file is a .txt document containing the new password you want to use. Follow the steps below:

1. Press the Windows key and search for Notepad. Press Enter to open the app.

2. Add the following line to the text file:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword';
  • Make sure to keep the quote marks and semicolon. Replace NewPassword with the password of your choice.
  • The localhost string makes the password change on your local system. If you’re changing the password on a system over the network, substitute localhost with the appropriate hostname.
Create a file with password command windows.

3. Save the file to the root of your hard drive (C: ). The filename should be mysql-init.txt.

Step 4: Open Command Prompt

1. Press the Windows key and type cmd.

2. From the search results, select the Run as administrator option to open Command Prompt as administrator.

Running Command Prompt as an administrator.

Step 5: Add New Parameters and Restart Server

1. Navigate to the MySQL directory using the command prompt:

cd "C:\Program Files\MySQL\MySQL Server 5.7\bin"

If you have a different MySQL version, make sure to use that version in the command.

2. Depending on how you installed MySQL, there are two ways to restart the server with the new parameters:

  • If you installed MySQL using the ZIP archive

Run the following command

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

Note that there are two slashes after the C: prompt.

  • If you installed MySQL using the MySQL Installation Wizard

You must specify a --defaults-file option in the command, followed by the path to the configuration file. Find the file path by right-clicking the MySQL service in the services list and selecting Properties:

The file path is listed in the Path to executable section. Copy the file path and use it in the command below, but make sure to use double slashes (\\) instead of single (\) in the path:

mysqld --defaults-file="C:\\ProgramData\\MySQL\\MySQL Server 5.7\\my.ini" --init-file=C:\\mysql-init.txt

3. Restart the MySQL service from the Services list. Right-click the MySQL service and select Start.

Step 6: Clean up

Now, log into your MySQL server as root using the new password. Once MySQL launches and you’ve confirmed the password change, delete the C:\mysql-init.txt file.

Conclusion

After reading this guide, you should be ready to reset the root password on MySQL in Linux and Windows. Whether you forgot your password or just want to change it for security reasons, it is an easy task that improves your database security.

Next, learn the difference between MySQL and PostgreSQL, or follow our guide and get started with MySQL Workbench on Ubuntu.

Was this article helpful?

YesNo

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Ranger file manager windows
  • Как убрать звук при изменении громкости на windows 10
  • Как примонтировать диск linux в windows
  • Пропала кнопка сменить пользователя windows 10
  • Ножницы для рабочего стола windows 10