开发者

mysql create user only when the user doesn't exist

开发者 https://www.devze.com 2023-01-31 22:36 出处:网络
I want to execute a CREATE USER statement, but only when the user doesn\'t alr开发者_运维百科eady exist.

I want to execute a CREATE USER statement, but only when the user doesn't alr开发者_运维百科eady exist.

What would be the best way of doing this?


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;


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消