Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Check if the user exists and drop it

Tags:

database

mysql

There’s not standard way to check if a MySQL user exists and based on that drop it. Are there any workarounds for this?

Edit: I need a straight way to run this without throwing up an error
e.g.

DROP USER test@localhost; :     
like image 398
Cherian Avatar asked Feb 28 '09 15:02

Cherian


People also ask

How to check if user exists in MySQL database?

To check how many users are present in MySQL, use MySQL. user table. The syntax is as follows to check how many users are present. Now you can check and drop the user if it exist.

How do you check if username already exists in php MySQL?

$query = mysql_query("SELECT username FROM Users WHERE username=$username", $con); if (mysql_num_rows($query) != 0) { echo "Username already exists"; } else { ... }


2 Answers

This worked for me:

GRANT USAGE ON *.* TO 'username'@'localhost'; DROP USER 'username'@'localhost'; 

This creates the user if it doesn't already exist (and grants it a harmless privilege), then deletes it either way. Found solution here: http://bugs.mysql.com/bug.php?id=19166

Updates: @Hao recommends adding IDENTIFIED BY; @andreb (in comments) suggests disabling NO_AUTO_CREATE_USER.

like image 120
treat your mods well Avatar answered Sep 24 '22 06:09

treat your mods well


Since MySQL 5.7 you can do a DROP USER IF EXISTS test

More info: http://dev.mysql.com/doc/refman/5.7/en/drop-user.html

like image 31
JavierCane Avatar answered Sep 22 '22 06:09

JavierCane