31 января, 2017 11:43 дп
22 995 views
| 2 комментария
Linux, MariaDB, mySQL
Если вы забыли или потеряли пароль пользователя root системы управления базами данных MySQL или MariaDB, вы можете получить доступ к данным, сбросив утерянный пароль. Для этого нужен доступ к серверу и учетная запись пользователя с поддержкой sudo.
Данное руководство поможет сбросить пароль пользователя root в MySQL и MariaDB.
Требования
Чтобы восстановить пароль MySQL или MariaDB, нужен:
- Доступ к серверу, на который установлена СУБД.
- Пользователь с поддержкой sudo.
1: Определение версии MySQL и MariaDB
Большинство современных дистрибутивов Linux поставляются с MySQL или MariaDB (аналог MySQL,полностью совместимый с этой БД). Способ восстановления пароля во многом зависит от версии СУБД.
Чтобы узнать версию программы, введите:
mysql --version
На экране появится такой вывод:
# MySQL
mysql Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using EditLine wrapper
# или MariaDB
mysql Ver 15.1 Distrib 5.5.52-MariaDB, for Linux (x86_64) using readline 5.1
Запишите название и версию СУБД: эти данные пригодятся в дальнейшем.
2: Остановка сервера БД
Чтобы изменить пароль root, отключите сервер баз данных.
# MySQL
sudo systemctl stop mysql
# MariaDB
sudo systemctl stop mariadb
3: Перезапуск базы данных без проверки привилегий
Если вы запустите MySQL или MariaDB, не загружая информацию о пользовательских привилегиях, вы сможете получить доступ к командной строке базы данных с привилегиями суперпользователя без пароля.
Для этого нужно предотвратить загрузку таблиц привилегий, в которых хранятся данные о привилегиях пользователя. Такой метод доступа подвергает сервер опасности, потому очень важно запретить подключения сети и других клиентов.
Чтобы запустить БД без таблиц привилегий, введите:
sudo mysqld_safe --skip-grant-tables --skip-networking &
Амперсанд (&) в конце команды переведёт её в фоновый режим, и вы сможете продолжить работу с терминалом.
Подключитесь к БД как root. Пароль не будет запрошен:
mysql -u root
Вы получите доступ к командной оболочке базы данных:
# MySQL
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
# MariaDB
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
4: Изменение пароля root
В современных версиях MySQL изменить пароль пользователя root можно с помощью команды ALTER USER. Однако данная команда не сработает без таблиц привилегий, которые вы отключили, чтобы получить доступ к БД.
Перезапустите таблицы привилегий с помощью команды:
FLUSH PRIVILEGES;
Теперь можно изменить пароль root.
В MySQL 5.7.6+ и MariaDB 10.1.20+ используйте команду:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
Примечание: Если команда ALTER USER не работает, это обычно свидетельствует о более серьезной проблеме. Вы можете попробовать изменить пароль с помощью UPDATE … SET.
UPDATE mysql.user SET authentication_string = PASSWORD('new_password') WHERE User = 'root' AND Host = 'localhost';
В MySQL 5.7.5, MariaDB 10.1.20 и более ранних версиях СУБД введите:
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');
Примечание: Вместо new_password укажите новый пароль пользователя root.
После этого нужно перезапустить таблицы привилегий.
После обновления пароля на экране должен появиться такой вывод:
Query OK, 0 rows affected (0.00 sec)
Пароль успешно изменен, так что теперь можно перезапустить сервер базы данных.
5: Перезапуск сервера
Остановите сервер баз данных, запущенный вручную в разделе 3. Эта команда находит (ID процесса) MySQL или MariaDB и отправляет SIGTERM, чтобы выйти после выполнения операции очистки.
Читайте также: Использование команд ps, kill и nice для управления процессами в Linux
# MySQL
sudo kill `cat /var/run/mysqld/mysqld.pid`
# MariaDB
sudo kill `/var/run/mariadb/mariadb.pid`
Теперь можно перезапустить сервис:
# MySQL
sudo systemctl start mysql
# MariaDB
sudo systemctl start mariadb
Убедитесь, что новый пароль работает:
mysql -u root -p
Команда должна запросить пароль пользователя root.
Заключение
Теперь вы знаете, как восстановить доступ суперпользователя к серверу MySQL и MariaDB.
Помните, что новый пароль должен быть сложным и уникальным.
Tags: MariaDB, MySQL
2025-04-26
Stop the MariaDB Service
- Using Services (Local)
- Open the Services app (search for «services.msc» in the Start menu).
- Locate the MariaDB service in the list.
- Right-click on it and select Stop.
Start MariaDB in Safe Mode
-
Save and restart MariaDB
Save the changes to the my.ini file.- Right-click on the MariaDB service in Services (Local) and select Start.
-
Edit the my.ini file
Open the file with a text editor (like Notepad) and add the following line under the[mysqld]
section:skip-grant-tables
-
Find the my.ini file
This file contains the configuration settings for your MariaDB server. Its location may vary depending on your installation, but common paths include:C:\Program Files\MariaDB\data\my.ini
C:\ProgramData\MariaDB\data\my.ini
Connect to MariaDB
-
Use the
mysql
command to connect to the MariaDB server:mysql -u root
- Since you’ve disabled password checks with
skip-grant-tables
, you won’t be prompted for a password.
- Since you’ve disabled password checks with
-
Open a command prompt or PowerShell window.
Update the Root Password
-
Inside the MariaDB shell:
USE mysql; UPDATE user SET Password=PASSWORD('your_new_strong_password') WHERE User='root'; FLUSH PRIVILEGES;
- Replace
your_new_strong_password
with your desired password.
- Replace
Stop and Restart MariaDB
- Save the changes and restart the MariaDB service.
- Edit the my.ini file again and remove the
skip-grant-tables
line. - Stop the MariaDB service in Services (Local).
Test the New Password
-
Try connecting to MariaDB using the
mysql
command:mysql -u root -p
- Enter your new password when prompted. If you can successfully connect, the password reset was successful.
Important Notes
- Backups
Before making any major changes to your MariaDB server, it’s highly recommended to create a backup of your data. - Security
After resetting the password, remove theskip-grant-tables
line from yourmy.ini
file as soon as possible. Leaving it enabled poses a significant security risk. - Strong Passwords
Choose a strong and unique password for your MariaDB root user. This is crucial for security.
Edit the my.ini file
-
Save and restart MariaDB
Save the file and restart the MariaDB service. -
Add skip-grant-tables
Open the file and add the following line under the[mysqld]
section:skip-grant-tables
-
Locate the my.ini file
This file contains MariaDB’s configuration settings.
Connect to MariaDB without a password
-
Use the
mysql
command to connect:mysql -u root
-
Open a command prompt or PowerShell.
Update the root password
-
In the MariaDB shell, execute the following SQL commands:
USE mysql; UPDATE user SET Password=PASSWORD('your_new_strong_password') WHERE User='root'; FLUSH PRIVILEGES;
- Replace
your_new_strong_password
with your desired password.
- Replace
Stop and restart MariaDB
- Restart the MariaDB service.
- Remove skip-grant-tables
Edit themy.ini
file, remove theskip-grant-tables
line, and save the changes. - Stop the MariaDB service.
Test the new password
-
Try connecting with the new password:
mysql -u root -p
- Enter your new password. If successful, the password reset is complete.
- FLUSH PRIVILEGES
This command refreshes the privilege tables, ensuring the password change takes effect immediately. - UPDATE user …
This SQL statement updates thePassword
field for theroot
user in themysql
database with the new password you provide. - skip-grant-tables
This directive temporarily disables password checks, allowing you to connect without a password. This is essential for resetting the password when you’ve lost it.
Important
- Strong Passwords
Choose a strong and unique password for maximum security. - Security
Removeskip-grant-tables
as soon as you’ve reset the password.
Using the ALTER USER Statement (Newer MariaDB/MySQL Versions)
-
Stop and Restart MariaDB
Stop and restart the MariaDB service as described previously. -
Update the Root Password
Use theALTER USER
statement:ALTER USER 'root'@'localhost' IDENTIFIED BY 'your_new_strong_password'; FLUSH PRIVILEGES;
-
Connect to MariaDB
Connect to the MariaDB server without a password:mysql -u root
-
Start MariaDB in Safe Mode
Follow the steps mentioned earlier to start MariaDB withskip-grant-tables
.
Using the SET PASSWORD Statement (Older Versions)
-
Stop and Restart MariaDB
Stop and restart the MariaDB service. -
Update the Root Password
Use theSET PASSWORD
statement:SET PASSWORD FOR 'root'@'localhost' = PASSWORD('your_new_strong_password'); FLUSH PRIVILEGES;
-
Connect to MariaDB
Connect without a password:mysql -u root
-
Start MariaDB in Safe Mode
Follow the same steps as before.
Key Considerations
- Version Compatibility
TheALTER USER
statement is generally preferred for newer versions of MariaDB and MySQL. - Security
Always removeskip-grant-tables
from themy.ini
file after resetting the password. - skip-grant-tables
This method is generally preferred due to its simplicity and compatibility across different versions.
Important Notes
- Always refer to the official MariaDB or MySQL documentation for the most accurate and up-to-date instructions.
- Choose the method that best suits your specific MariaDB or MySQL version and your preferred syntax.
- These alternative methods provide similar functionality to the
UPDATE user
method.
mariadb
Если у вас 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%)
- Как настроить PHP для работы с get_browser (browscap.ini) в Windows (RANDOM — 50%)
In this MariaDB tutorial, we will learn about the MariaDB reset root password and cover the following topics.
- MariaDB reset root password windows
- MariaDB reset root password ubuntu
- MariaDB reset root password mac
- MariaDB reset root password docker
- MariaDB reset root password Linux
- MariaDB reset root password xampp
- MariaDB reset root password Debian 9
- MariaDB 10.3 reset root password
In this section, we will learn how to reset the password of MariaDB. Sometimes, we forget the password, so will recover the password of MariaDB that running on a Windows machine. To recover the password we must have access to that MariaDB server.
Follow the below steps to reset the password.
Firstly, check the version of the MariaDB server by opening the command line on windows and typing the below command in that command line.
mysql --version
If unable to run this command in the command line, then go to the C:\Program Files\MariaDB 10.6
folder of MariaDB where it is installed on your windows machine and from the folder we can see it is MariaDB 10.6 version.
Secondly, stop the database server by opening the command line as the administrator, typing the below code.
net stop MairaDB
If the MariaDB version is 10.4 or a later version then run the above code, for the MariaDB version before 10.4 run the below code to stop the database server.
net stop MySQL
Here we are using the MariaDB 10.6 version so we will run the command net stop MariaDB
.
Thirdly, restart the MariaDB server without loading the grant tables like user and db, these grant tables contain information about the user privileges that who can log in and has access to which database.
When the MariaDB server restarts without user privileges information or grant tables, then any user can log in to MariaDB using the command line without a password as the root user. Additionally, we will also skip the network while restarting MariaDB so that other users can’t connect to this server.
Go to the bin
folder of MariaDB (C:\Program Files\MariaDB 10.6\bin)
where it is installed. open the command line and type the below code to restart the MariaDB server without grant tables.
cd C:\Program Files\MariaDB 10.6\bin
./mysqld --skip-grant-tables --skip-networking --shared-memory
Fourthly, let’s reset the password of MariaDB, open the command line, and type the below code to log in as a root user without a password.
mysql -u root
After running the above code in the command line, we have logged into MariaDB as a root user that we can see in the below output.
Before resetting the password, load the grant tables that contain information about user privileges. Run the below code to reload the grant tables in MariaDB prompt.
FLUSH PRIVILEGES;
Reset the password using the below code.
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_user_password';
If the MariaDB version is 10.1.20 or later then use the above code, otherwise use the below code for MariaDB version 10.1.20.
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_user_password');
Again reload the grant tables using the below code.
FLUSH PRIVILEGES;
After running the above code, it shows the output as Query OK, 0 rows affected (0.011 sec)
.
Exit from the MariaDB prompt or session.
exit
We have reset the password of MariaDB manually. Now restart the MariaDB server normally by opening the command line as administrator and typing the below code in that command line.
net start MariaDB
Login with a new password in MariaDB by typing the below command in the command line.
mysql -u root -p
If the above command asks for a password then enter the new password that we reset for the root user in the above steps.
From the output, we can see that we have successfully reset the password of MariaDB.
Also, check: MariaDB Backup Database
MariaDB Reset Root Password Ubuntu
To reset the password of MariaDB on Ubuntu some of the commands are the same for MariaDB that we have used in the above sub-section. Follow the below steps to reset the password of MariaDB on Ubuntu.
First, check the version of MariaDB using by opening the terminal and typing the below code in that terminal.
mysql --version
Stop the MariaDB server, so we can reset the password of MariaDB manually. Use the below code to stop the database server.
sudo systemctl stop mariadb
After stopping the MariaDB server, run the below code to restart the MariaDB server without grant tables. When the MariaDB server restarts without user privileges information or grant tables, then any user can log in to MariaDB using the command line without a password as the root user.
Additionally, we will also skip the network while restarting MariaDB so that other users can’t connect to this server.
sudo mysqld_safe --skip-grant-tables --skip-networking &
Login into the MariaDB prompt without entering the password by typing the below code in the same terminal.
mysql -u root
Now we can reset the password of MariaDB because we logged in as a root user so we have full access to the database.
Before resetting the password, reload the grant table using the below code.
FLUSH PRIVILEGES;
Reset the password using the below code.
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_user_password';
If the MariaDB version is 10.1.20 or later then use the above code, otherwise use the below code for MariaDB version 10.1.20.
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_user_password');
Again reload the grant tables using the below code.
FLUSH PRIVILEGES;
After running the above code, it shows the output as Query OK, 0 rows affected (0.001 sec)
.
Exit from the MariaDB prompt or session.
exit
We have reset the password of the MariaDB server manually, After this, restart the MariaDB server in normal mode by restarting the Ubuntu machine. Run the below code to check the status of the MariaDB server.
systemctl status mariadb
Then login into the MariaDB server with a new password.
mysql -u root -p
From the output, we can see that we have successfully login into MariaDB with a new password.
Read: MariaDB Enable Remote Access
MariaDB Reset Root Password Mac
To reset the root password in Mac OS, follow the steps provided in the above subsection “MariaDB reset root password Ubuntu”.
MariaDB Reset Root Password Docker
To reset the root password of MariaDB follow the below steps.
Open the docker-compose file for MariaDB and add the line command: --skip-grant-tables
at the end of the file as given in the below output.
# Use root/example as user/password credentials
version: '3.1'
services:
db:
image: mariadb
restart: always
environment:
MYSQL_ROOT_PASSWORD: example
ports:
- 8080:8080
command: --skip-grant-tables
After adding the line, restart the container MariaDB using the below code in the directory where the above compose file exists.
docker-compose down -- to stop the running container
Then start the container.
docker-compose up -- to start the container with new setting
Access the bash shell of the MariaDB container by clicking on the button CLI
in docker application.
Login into MariaDB as root user using the below code.
mysql -u root
Before resetting the password, reload the grant table using the below code.
FLUSH PRIVILEGES;
Reset the password using the below code.
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_user_password';
If the MariaDB version is 10.1.20 or later then use the above code, otherwise use the below code for MariaDB version 10.1.20.
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_user_password');
Again reload the grant tables using the below code.
FLUSH PRIVILEGES;
After running the above code, it shows the output as Query OK, 0 rows affected (0.011 sec)
.
Exit from the MariaDB prompt or session.
exit
After performing the above steps, exit the bash shell of the MariaDB container, stop the MariaDB container and open the docker-compose file, remove the line command: --skip-grant-tables
from the file and save the file. Then restart the container again with changes setting using the below code.
sudo nano docker-compose file -- opening the compose file
Then start the container.
docker-compose up -- to start the container with new setting
Again access the bash shell of the MariaDB container using the below code or use the docker desktop application to open the base shell of that container.
docker exec -it mariadbtips-db-1 bash
Login into MariaDB as root user with a new password using the below code.
mysql -u root -p
Read: MariaDB Check If Rows Exists
MariaDB Reset Root Password Linux
To reset the root password of MariaDB in Linux, follow the steps of the tutorial “MariaDB reset root password Ubuntu” because all Linux-based operating systems follow the same steps to reset the password of MariaDB.
MariaDB Reset Root Password xampp
The XAMPP is a cross-platform web server developed by Apache. So here we will reset the password of MariaDB using XAMPP shell and for that follow the below steps.
Open the XAMPP control panel on your system and click on the button Conifg
of MySQL, then option appears as my.ini
and click on my.ini
option to open the file as shown in the below picture.
After opening the file, add the given line below the line [mysqld]
of file my.ini
and save the file.
skip-grant-tables
Then come back to the XAMPP control panel, stop and start the MySQL server to take effect on changes that we made. After this, we will be able to log into the database without a password as the root user.
Click on the button Shell
to open the shell, check the version, and login into the database without a password.
Before resetting the password, reload the grant table using the below code.
FLUSH PRIVILEGES;
Reset the password using the below code.
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_user_password';
If the MariaDB version is 10.1.20 or later then use the above code, otherwise use the below code for MariaDB version 10.1.20.
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_user_password');
Again reload the grant tables using the below code.
FLUSH PRIVILEGES;
After running the above code, it shows the output as Query OK, 0 rows affected (0.000 sec)
.
Exit from the MariaDB prompt or session.
exit
Then again open the file my.ini
and remove the line skip-grant-tables
and restart the MySQL server.
Login with a new password that we set for the root user in the above steps.
mysql -u root -p
Now we have successfully logged into the database with a reset password.
Read: MariaDB Truncate Table + Examples
MariaDB reset root password Debian 9
The same steps are used to reset the password of MariaDB in Debian 9 as we have used the above sub-section “MariaDB reset root password Ubuntu”.
Read: MariaDB Rename View
MariaDB 10.3 Reset Root Password
So in this section, we will reset the root password of MariaDB 10.3
and follow the below steps.
Firstly, check the version of the MariaDB server by opening the command line on windows and typing the below command in that command line.
mysql --version
If unable to run this command in the command line, then go to the C:\Program Files\MariaDB 10.3
folder of MariaDB where it is installed on your windows machine and from the folder we can see it is MariaDB 10.3 version.
Secondly, stop the database server by opening the command line as the administrator, typing the below code.
net stop MairaDB
If the MariaDB version is 10.4 or a later version then run the above code, for the MariaDB version before 10.4 run the below code to stop the database server.
net stop MySQL
Here we are using the MariaDB 10.6 version so we will run the command net stop MariaDB
.
Thirdly, restart the MariaDB server without loading the grant tables like user and db, these grant tables contain information about the user privileges that who can log in and has access to which database.
When the MariaDB server restarts without user privileges information or grant tables, then any user can log in to MariaDB using the command line without a password as the root user. Additionally, we will also skip the network while restarting MariaDB so that other users can’t connect to this server.
Go to the bin
folder of MariaDB (C:\Program Files\MariaDB 10.6\bin)
where it is installed. open the command line and type the below code to restart the MariaDB server without grant tables.
cd C:\Program Files\MariaDB 10.6\bin
./mysqld --skip-grant-tables --skip-networking --shared-memory
Fourthly, let’s reset the password of MariaDB, open the command line, and type the below code to log in as a root user without a password.
mysql -u root
After running the above code in the command line, we have logged into MariaDB as a root user that we can see in the below output.
Before resetting the password, load the grant tables that contain information about user privileges. Run the below code to reload the grant tables in MariaDB prompt.
FLUSH PRIVILEGES;
Reset the password using the below code.
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_user_password';
If the MariaDB version is 10.1.20 or later then use the above code, otherwise use the below code for MariaDB version 10.1.20.
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_user_password');
Again reload the grant tables using the below code.
FLUSH PRIVILEGES;
After running the above code, it shows the output as Query OK, 0 rows affected (0.011 sec)
.
Exit from the MariaDB prompt or session.
exit
We have reset the password of MariaDB manually. Now restart the MariaDB server normally by opening the command line as administrator and typing the below code in that command line.
net start MariaDB
Login with a new password in MariaDB by typing the below command in the command line.
mysql -u root -p
If the above command asks for a password then enter the new password that we reset for the root user in the above steps.
From the output, we can see that we have successfully reset the password of MariaDB.
You may also like to read the following MariaDB tutorials.
- MariaDB Left Join
- MariaDB Rename Column
- MariaDB Truncate Table
- MariaDB Union Operator
- MariaDB Case Statement
- MariaDB Variables Tutorial
- MariaDB Temporary Table
So, in this tutorial, we have learned about the “MariaDB reset root password“, learned how to reset the MariaDB on different systems, and covered the following topics.
- MariaDB reset root password windows
- MariaDB reset root password ubuntu
- MariaDB reset root password mac
- MariaDB reset root password docker
- MariaDB reset root password Linux
- MariaDB reset root password xampp
- MariaDB reset root password Debian 9
- MariaDB 10.3 reset root password
I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.
Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.
Updated April 12, 2023
Introduction to MariaDB reset root password
MariaDB Reset Root Password is the MariaDB command which helps to recover the entrance to the server whenever the user loses or forgets the root password of the MariaDB server. With this MariaDB Reset Root Password, one can still gain excess to the MariaDB server by resetting the password of the root account if the user account is a sudo-enabled. The MariaDB Reset Root Password is performed by using different commands to recover the root password which depends on the version of MySQL server that is running on the user’s system. The need to have the root user privileges to reset the root password in MariaDB server when a user needs to change it or does not remember the set password.
Syntax
Let us discuss the steps to be followed for resetting the password to new one in MariaDB server as follows:
There are some prerequisites for recovering the MariaDB root password that needs to be operated listed as follows:
Having access to the Linux server functioning MariaDB or MySQL holding a sudo user.
- Recognizing the Database version: On the basis of the database implemented and its version, the user requires to apply several commands to reset the root password. Here, we can test the version of the MariaDB server using the succeeding command as: mysql –version
The output for this using MariaDB will be:
mysql Ver 15.1 Distrib 5.5.52-MariaDB, Linux (x86_64) using readline 5.1
- Discontinuing the Database server: Here, for modifying the root password in the server we need to shut down the MariaDB database server before and for this we need to use command as follows in MariaDB: Sudo systemctl stop mariadb. After this when the server has been stopped, we can access it for resetting the root password manually.
- Without Permission check restart the database server: When the user executes MariaDB but not loading information regarding the root privileges then, it will permit to manage the database command line having root privileges and not delivering the password. This will make you to access the server but not knowing it. We will start the database table but not loading the grant tables which stores information of user privileges or enabling networking as: sudo mysqld_safe –skip-grant-tables –skip-networking &, using ampersand in the command at the end will proceed the process to run in the background hence continuing using the terminal.
- Altering the root password: For modern MySQL versions we can change the root user password in a simple way applying the command ALTER USER. But without loading the grant tables, this will not work. Therefore, we will reload it by allotting the command FLUSH PRIVILEGES.
After that set any new password to the root user using the following command but for MySQL 5.7.6 version and MariaDB 10.1.20 and later ones:
ALTER USER 'root@localhost' IDENTIFIED BY 'novel_password';
FLUSH PRIVILEGES;
Also, for version MySQL 5.7.5 or MariaDB 10.1.20 and earlier ones:
SET PASSWORD FOR 'root@localhost' = PASSWORD(‘novel_password’);
FLUSH PRIVILEGES;
OK will be resulted if everything goes well in both the above cases for password reset of user root.
- Restart the database routinely: Firstly, we need to stop the illustration of the database server which was initiated manually in third step as: sudo systemctl start mariadb.
- In MariaDB, with this the user has administrative access to the MariaDB server renovated. This time we need to be ensure if the new root password chosen is robust & secure and should be kept safely.
How to reset the root password in MariaDB?
- There is slight difference between changing the password and resetting the password in general definition. Suppose, when you have the root password, one can easily establish connection to the database logging as the root user where one can change the password simply. Not only the root password, one can change any other user account password too.
- But what to do when a user forgets the password of the root user? This means that the root user will not be able to connect to the MariaDB server unless password is correct or valid one. Here, the root user holds the utmost privileges so therefore, no one can alter its password using any other accounts. Thus, in this condition we require to perform few supplementary steps for resetting the MariaDB root password.
- The MariaDB is assembled on upper level of MySQL. It is very prevalent for web hosting necessities. So, the steps to reset the password in MariaDB will be similar like MySQL also. Hence, any SQL query command which functions for MySQL will also work as well for MariaDB. But only the alteration that need to be done in the commands is to start and stop of MySQL server.
- If the user is working on Windows OS, then we need to use mysqladmin or mysqld through the command prompt for starting or stopping the MySQL server, which are positioned in the MariaDB installation bin folder in the system.
Examples
Let us provide an example explaining the query how it resets the MariaDB user account password with super privileges on forgetting it with the command as follows:
Firstly, we have a list of user accounts present in my phpmyadmin MariaDB server shown as below:
As you can view there are few users apart from the global super user root such as slaveuser and technouser. Let us then take a demonstration for resetting the technouser password as the password is forgotten is supposed.
So, the MariaDB reset root password will follow the similar steps as mentioned above in the syntax section and then the reset main query will be as:
ALTER USER 'tchnouser@localhost' IDENTIFIED BY 'techno@123';
FLUSH PRIVILEGES;
Conclusion
- In MariaDB or MySQL, the root user is also like any other user available in the server account. Perhaps, since it is known to be the super user, so altering or resetting its password might be bit tricky and one cannot modify the root password from other user login accounts.
- Hence, this MariaDB Reset Root Password helps to recover the forgotten password in the server and apply new one with super user privilege.
Recommended Articles
We hope that this EDUCBA information on “MariaDB reset root password” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
- MariaDB Delete User
- MariaDB IF
- MariaDB MaxScale
- MariaDB UPDATE