mysql 如果不存在则创建用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13357760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:27:09  来源:igfitidea点击:

mysql create user if not exists

mysqluser-management

提问by sweb

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

我有一个查询来检查 mysql 用户列表以创建新用户。

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

回答by Ascherer

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

在 5.7.6 及以上版本中,您应该可以使用 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.

请注意,5.7.6 方法实际上并未授予任何权限。



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

如果您没有使用具有此功能的版本(低于 5.7.6),您可以执行以下操作:

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 ALLmethod will not create a user.

请注意,如果您使用的是 MySQL 8,则该GRANT ALL方法不会创建用户。

回答by ingocnito

I use

我用

SELECT EXISTS (SELECT DISTINCT userFROM mysql.userWHERE user= "username") as is_user

SELECT EXISTS(SELECT DISTINCT userFROM mysqluserWHERE user= “用户名”)作为is_user

should return 1 if exists or 0 if it does not

如果存在则返回 1,否则返回 0