How to delete user mysql

How to delete user mysql

How to delete user mysql

The DROP USER statement removes one or more MySQL accounts and their privileges. It removes privilege rows for the account from all grant tables.

Roles named in the mandatory_roles system variable value cannot be dropped.

As of MySQL 8.0.22, DROP USER fails with an error if any account to be dropped is named as the DEFINER attribute for any stored object. (That is, the statement fails if dropping an account would cause a stored object to become orphaned.) To perform the operation anyway, you must have the SET_USER_ID privilege; in this case, the statement succeeds with a warning rather than failing with an error. For additional information, including how to identify which objects name a given account as the DEFINER attribute, see Orphan Stored Objects.

DROP USER either succeeds for all named users or rolls back and has no effect if any error occurs. By default, an error occurs if you try to drop a user that does not exist. If the IF EXISTS clause is given, the statement produces a warning for each named user that does not exist, rather than an error.

The statement is written to the binary log if it succeeds, but not if it fails; in that case, rollback occurs and no changes are made. A statement written to the binary log includes all named users. If the IF EXISTS clause is given, this includes even users that do not exist and were not dropped.

Each account name uses the format described in Section 6.2.4, “Specifying Account Names”. For example:

DROP USER does not automatically drop or invalidate databases or objects within them that the old user created. This includes stored programs or views for which the DEFINER attribute names the dropped user. Attempts to access such objects may produce an error if they execute in definer security context. (For information about security context, see Section 25.6, “Stored Object Access Control”.)

Как правильно удалить пользователя MySQL

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

Авторизация в MySQL с правами суперпользователя

Просмотр записей

Чтобы не ошибиться, предварительно посмотрите, какие профили есть на сервере БД. В MySQL просмотр пользователей выполняется командой:

В списке отобразится имя и адрес хоста. Информация представлена в виде обычной таблицы.

Просмотр разрешений

Допустим, вам нужно в MySQL удалить пользователя с именем `timeweb@localhost`. Сначала проверьте, какие у него есть разрешения:

В ответе вернется таблица с описанием прав — например, что у этого аккаунта есть все привилегии в базе данных `timeweb_db`.

Отзыв разрешений

Вы получили через MySQL список пользователей и прав. Дальше нужно решать, что делать с профилем. Необязательно удалять его. Можно для начала отозвать привилегии. Учетка останется, но будет ограниченной.

Чтобы отозвать разрешения, выполните команду:

Вместо ‘timeweb’@’localhost’ подставьте имя пользователя, у которого нужно отобрать возможность управлять таблицами и базами данных.

В ответ должен вернуться статус:

Можно проверить, все ли корректно, запросив список привилегий еще раз:

Удаление аккаунта MySQL

Если пользователь не нужен, удалите его:

В ответ должно вернуться:

Можно проверить, все ли корректно, запросив список профилей:

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

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

How To Remove or Delete a MySQL User Account

Home » Databases » MySQL » How To Remove or Delete a MySQL User Account

It’s essential to have control over who has access to a database.

To delete a MySQL user is to remove an account and its privileges from all grant tables. Only users with global CREATE USER or DELETE privileges can perform such tasks. In this tutorial, learn how to remove MySQL user accounts using the DROP USER statement.

How to delete user mysql. Смотреть фото How to delete user mysql. Смотреть картинку How to delete user mysql. Картинка про How to delete user mysql. Фото How to delete user mysql

Deleting a MySQL Account

1. First, connect to the MySQL database as the root user:

If root does not have access to MySQL on your machine, you can use sudo mysql

2. Enter the password when prompted and hit Enter. A MySQL shell loads.

3. Find the exact name of the user you want to remove by running a command that lists users from the MySQL server:

How to delete user mysql. Смотреть фото How to delete user mysql. Смотреть картинку How to delete user mysql. Картинка про How to delete user mysql. Фото How to delete user mysql

4. The output displays all users. Locate the name you want to remove, in our case it is MySQLtest. Replace username in the following command with your user:

5. Recheck the user list to verify the user was deleted.

How to delete user mysql. Смотреть фото How to delete user mysql. Смотреть картинку How to delete user mysql. Картинка про How to delete user mysql. Фото How to delete user mysql

DROP USER Syntax

The basic syntax for the DROP USER statement is:

Remove Multiple MySQL Users

To delete multiple users at the same time, use the same DROP USER syntax, and add users separated by a comma and a space.

Note: If you removed an existing MySQL account and want to create a new one, refer to our article on How to Create MySQL Account and Grant Privileges.

Drop a Connected / Active User

If the user you want to remove from the MySQL database is active at that time, its privileges will be revoked only once the session is closed. After that, the user will not have access to the database.

If you want the DROP USER statement to go into effect immediately, you need to kill the user session and then remove the account.

1. Find the connection ID for the unwanted user. Prompt a list to see all activity processes and their IDs:

How to delete user mysql. Смотреть фото How to delete user mysql. Смотреть картинку How to delete user mysql. Картинка про How to delete user mysql. Фото How to delete user mysql

2. Locate the Id of the user and add the number to the kill command to kill the process in MySQL:

3. Once the user is no longer active, you can remove it from the MySQL database with:

In this article, you have learned how to delete one or multiple MySQL user accounts, as well as how to remove active accounts.

For more ways to optimize your MySQL Database, read our MySQL Performance Tuning tutorial.

How To Remove User Accounts Using MySQL DROP USER Statement

Summary: in this tutorial, you will learn how to use the MySQL DROP USER statement to remove one or more user accounts from the database.

Introduction to MySQL DROP USER statement

To remove a user account from the MySQL Server, you use the DROP USER statement as follows:

How to delete user mysql. Смотреть фото How to delete user mysql. Смотреть картинку How to delete user mysql. Картинка про How to delete user mysql. Фото How to delete user mysql

In this syntax, you specify the name of the user account that you want to remove after the DROP USER keywords.

If you want to remove multiple user accounts at once, you specify a list of comma-separated user accounts in the DROP USER clause:

If you remove a user account that doesn’t exist, MySQL will issue an error.

In MySQL 5.7.8+, you can use the IF EXISTS clause to conditionally drop a user only if it exists:

Besides removing the user account, the DROP USER statement also removes all privileges of the user from all grant tables.

MySQL DROP USER examples

Let’s take some examples of dropping users.

A) Using MySQL DROP USER statement to drop a user example

First, connect to the MySQL Server using the root account:

Type the password for the root user and press Enter :

Third, show users from the MySQL Server:

Here is the current user list:

Fourth, drop the user dbadmin@localhost by using the DROP USER statement:

Fifth, show all users again:

The user account dbadmin@localhost has been removed successfully.

B) Using MySQL DROP USER to drop multiple user accounts at once

First, remove two user accounts api@localhost and remote using the following statement:

Second, show users from the current database:

Here is the output:

C) Using MySQL DROP USER to drop a connected user

Second, select the people database:

Third, create a new table persons in the people database:

Fourth, grant all privileges on the people database to the account user alice :

Fifth, launch another session and connect to the database using the user alice@localhost :

Type the password for the user account alice and press the Enter key:

Sixth, select the people database:

Seventh, insert a row into the persons table:

However, the user account alice@localhost is still connected to MySQL Server. If you drop a currently connected user, the user can operate as normal until the next login. In this case, you should inform the user first.

If you cannot do so, you can kill user sessions first before dropping the user account.

Eighth, use the SHOW PROCESSLIST statement from the root’s session to find the id of the connection:

Ninth, terminate process 21 by using the KILL statement:

The user account alice received an error message if he/she issue any query:

In this tutorial, you have learned how to use the MySQL DROP USER statement to remove one or more user accounts.

Как удалить учетные записи пользователей MySQL

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

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

В этом руководстве объясняется, как удалить учетные записи пользователей MySQL / MariaDB.

Заявление DROP USER

Например, чтобы удалить учетную запись пользователя [email protected] войдите в оболочку MYSQL и запустите:

В случае успеха команда вернет:

Чтобы удалить несколько учетных записей пользователей с помощью одной команды, запустите оператор DROP USER а затем укажите пользователей, которых вы хотите удалить, через пробел:

Если вы попытаетесь удалить учетную запись пользователя, которая не существует, а предложение IF EXISTS не используется, команда вернет ошибку.

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

Созданные пользователем базы данных и объекты не удаляются автоматически.

Удаление учетных записей пользователей MySQL

В этом разделе приведены пошаговые инструкции о том, как составить список и удалить учетные записи пользователей MySQL.

Сначала войдите в оболочку MySQL от имени пользователя root или другого администратора. Для этого введите следующую команду:

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

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

Результат должен выглядеть примерно так:

Допустим, [email protected] запись пользователя [email protected] больше не нужна, и мы хотим ее удалить.

Чтобы удалить пользователя, выполните:

Команда удалит учетную запись пользователя и ее привилегии.

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

Выводы

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

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *