mysql create user if not exists

前端 未结 2 361
醉梦人生
醉梦人生 2020-12-23 11:02

I have a query to check mysql users list for create new user.

IF (SELECT EXISTS(SELECT 1 FROM `mysql`.`user` WHERE `user` = \'{{ title }}\')) = 0 THEN
    CR         


        
相关标签:
2条回答
  • 2020-12-23 11:41

    I use

    SELECT EXISTS (SELECT DISTINCT user FROM mysql.user WHERE user = "username") as is_user

    should return 1 if exists or 0 if it does not

    0 讨论(0)
  • 2020-12-23 11:42

    In 5.7.6 and above, you should be able to use CREATE USER

    CREATE USER IF NOT EXISTS 'user'@'localhost' IDENTIFIED BY 'password';
    

    Note that the 5.7.6 method doesn't actually grant any permissions.


    If you aren't using a version which has this capability (something below 5.7.6), you can do the following:

    GRANT ALL ON `database`.* TO 'user'@'localhost' IDENTIFIED BY 'password';
    

    This will create the user if it doesn't exist


    Note, if you are on MySQL 8, the GRANT ALL method will not create a user.

    0 讨论(0)
提交回复
热议问题