Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql create user only when the user doesn't exist

Tags:

sql

mysql

I want to execute a CREATE USER statement, but only when the user doesn't already exist.
What would be the best way of doing this?

like image 874
trobrock Avatar asked Dec 24 '10 21:12

trobrock


2 Answers

If you're creating a user, you need to create a grant too. The grant implicitly creates a user if it doesn't exist (which is why you are encouraged to include the password when creating a grant, just in case they don't exist). see http://dev.mysql.com/doc/refman/5.1/en/grant.html

So an option is to just create the grant (with the password) and the user is implicitly created.

E.g:

GRANT ALL PRIVILEGES  ON db_name.* 
TO 'user'@'%' IDENTIFIED BY 'password' 
WITH GRANT OPTION;
like image 115
Tim Diggins Avatar answered Oct 07 '22 00:10

Tim Diggins


You can select from the "user" table on the default mysql database. Like this:

select *
from user
where User = 'username'

If no results are returned, create a new user.

like image 28
AaronM Avatar answered Oct 07 '22 01:10

AaronM