mysql create user only when the user doesn't exist

后端 未结 2 1318
别那么骄傲
别那么骄傲 2021-02-13 18:41

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?

相关标签:
2条回答
  • 2021-02-13 18:58

    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 讨论(0)
  • 2021-02-13 19:00

    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;
    
    0 讨论(0)
提交回复
热议问题