mysql create user if not exists

▼魔方 西西 提交于 2019-12-03 01:47:15

问题


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
    CREATE USER '{{ title }}'@'localhost' IDENTIFIED BY '{{ password }}'
END IF;

But i get this error:

ERROR 1064 (42000) at line 3: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF (SELECT EXISTS(SELECT 1 FROM `mysql`.`user` WHERE `user` = 'cms_localhost')) = 0 ' at line 1

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/13357760/mysql-create-user-if-not-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!